Whenever I type std::getline in Visual Studio, getline gets a red underline and the program will not run. The same code works for a friend using another C++ editor. Here is the program:
#include
int main() {
std::string name;
std::cout < 15) {
std::cout << "Your name can't be over 15 characters";
} else {
std::cout << "Welcome " << name;
}
return 0;
}
Is there something I need to configure in Visual Studio, or is there another way to read a full line of text?
3 Answers
You need to include the string header explicitly. Add #include near the top:
#include
#include
std::getline is declared through the string-related standard library headers, and relying on another header to include it indirectly can work with one compiler but fail with another. Also check the actual compiler error, since it usually points directly to the missing declaration.
Make sure the .cpp file is part of a properly configured C++ project in Visual Studio, rather than just opening the file by itself. The code should compile once it is in a C++ project and includes both and . You do not need an alternative to std::getline; it is the normal way to read a complete line, including spaces.
You can keep writing std::cout, std::cin, std::string, and std::getline exactly as you have them. Adding using namespace std; would shorten the code, but it is generally better for beginners to keep the std:: prefix because it makes it clear where those names come from and avoids name conflicts.

So adding #include should be enough? I’ll try that.