Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::getline on std::cin

Tags:

c++

getline

cin

Is there any good reason why:

std::string input;
std::getline(std::cin, input);

the getline call won't wait for user input? Is the state of cin messed up somehow?

like image 654
ForeverLearning Avatar asked Jul 25 '11 16:07

ForeverLearning


People also ask

Can you use Getline with CIN?

The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.

Should I use getline or cin?

The main difference between getline and cin is that getline is a standard library function in the string header file while cin is an instance of istream class. In breif, getline is a function while cin is an object. Usually, the common practice is to use cin instead of getline.

What is CIN Getline in C++?

C++ getline() The cin is an object which is used to take input from the user but does not allow to take the input in multiple lines. To accept the multiple lines, we use the getline() function. It is a pre-defined function defined in a <string.


1 Answers

Most likely you are trying to read a string after reading some other data, say an int.

consider the input:

11
is a prime

if you use the following code:

std::cin>>number;
std::getline(std::cin,input)

the getline will only read the newline after 11 and hence you will get the impression that it's not waiting for user input.

The way to resolve this is to use a dummy getline to consume the new line after the number.

like image 192
Shamim Hafiz - MSFT Avatar answered Oct 10 '22 08:10

Shamim Hafiz - MSFT