cin buffer problem

closed account (EAXiz8AR)
Here is a simple program that I can't seem to get working. If you run the program, it works fine until the age question, where after I type in my age, the program simply outputs the next question, "Please enter your country of origin", without allowing the user to type in an answer for the country.

I think this is a cin buffer problem and I tried tinkering with it but it still doesn't work. Can you guys help me? thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;


int main()
{
char question[] = "Please enter your first name: ";
char firstname[50];
char lastname[50];
char greet1[] = "Hello, ";
char greet2[] = "! Please enter your last name: ";
char greet3[] = "Welcome to Gondor, ";

int age;
string country;

cout << question;
cin >> firstname;
cout << greet1 << firstname << greet2;
cin >> lastname;
cout << greet3 << firstname << " " << lastname << "!\n";

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


return 0;


}
Last edited on
'getline' retrives what is already in the buffer. It doesn't wait for input like cin. Why not just use cin like u did for the other questions ?
Last edited on
when you press enter after entering the age,'\n' is saved in input buffer.
getline gets input from input buffer which has '\n'.Thus it ends.

To avoid this you can use cin.ignore(); before getline function.
Topic archived. No new replies allowed.