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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With