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?
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?
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.
std::getline
for reading any input, and never use std::cin >>
style input. For reading an int, you can read the line in a string buffer, and then parse that buffer to get the int out of it (using std::stringstream
eg.). –
Orle cin.ignore(1, '\n');
. –
Foretooth operator>>
preceding a call to getline
, leaving a '\n' in the input buffer. –
Tipi I have tested the following code and it worked ok.
#include <iostream>
using namespace std;
int main()
{
string input;
getline(cin, input);
cout << "You input is: " << input << endl;
return 0;
}
I guess in your program that you might already have something in you input buffer.
This code does not work:
#include <iostream>
#include <string>
int main()
{
int nr;
std::cout << "Number: ";
std::cin >> nr;
std::string input;
std::cout << "Write something: ";
getline(std::cin, input);
std::cout << "You input is: " << input << std::endl;
return 0;
}
This does work:
#include <iostream>
#include <string>
int main()
{
int nr;
std::cout << "Number: ";
std::cin >> nr;
std::string x;
std::getline(std::cin,x);
std::string input;
std::cout << "Write something: ";
getline(std::cin, input);
std::cout << "You input is: " << input << std::endl;
return 0;
}
this occurred cause before std::getline(std::cin, input); there's newline char (/n). The getline reads until it encounters /n. Therefore it will read an empty string and return null without waiting for the users input.
To counter this we use an dummy getline, or cin.ignore(1, /n);
© 2022 - 2024 — McMap. All rights reserved.
'\n'
sitting in the input buffer from before, perhaps? – Banjermasincin
is allowed to be buffered. Many implementations require a newline in order to flush the input buffer and return the data to the calling program. – Convulsion