Why does Visual Studio underline std::getline in my C++ code?

0
12
Asked By MellowCactus47 On

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

Answered By BlueOrbit9 On

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.

MellowCactus47 -

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

Answered By QuietPixel22 On

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.

Answered By RavenToast6 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.