cin buffer problem

closed account (EAXiz8AR)
Ok so I have this problem where if the user inputs two words, only the first word is outputted. I tried solving it by editing my program to the one below, but it still doesn't work. Can you guys help me fix this so that it outputs two words, and not just the first word?

Specifically, when the user enters something like "United States" into "country", only "United" is outputted.

thanks



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{

int age;
string country;

cout << "Please enter your age: ";
cin >> age;
cout << "Please enter your country of origin: ";
getline (cin, country);
cout << "Age is: " << age << "and country is: " << country << endl;

return 0;

}

Have you tried flushing the buffer?
When you press enter a new line character is added to the stream. cin >> age; only reads the first integer and leaves the new line character still in the stream. getline(cin, country); reads until it finds the first new line character. The first character it finds is a new line character so it returns right away making country an empty string (I don't really get how it can be "United" for you). What you have to do is remove the new line character that was left from the first line. You can do that by using ignore somewhere between line 8 and 10.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Topic archived. No new replies allowed.