cin.getline problem

What's the problem with the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main()
{
int a;
char str1[20];
char str2[20];

cout<<"Enter an integer:\n";
cin>>a;
cout<<"Enter str1:\n";
cin.getline(str1,20,'\n');
cout<<"Enter str2:\n";
cin.getline(str2,20,'\n');
return 0;
}

Above program reads a and str2 but skips str1. Why???
You are mixing formatted ( >> ) and unformatted ( getline ) input, you shouldn't: http://www.cplusplus.com/forum/articles/6046/
Sample input stream:

10\nHello World\nGoodbye World\n

cin >> a;

consumes 10, leaving

\nHello World\nGoodbye World\n

cin.getline( str1, 20, '\n' );

consumes \n, leaving

Hello World\nGoodbye World\n

cin.getline( str2, 20, '\n' );

consumes Hello World\n, leaving

Goodbye World\n
The easiest fix for that is to clear the keyboard buffer after the cin. Do it with cin.ignore();.

int main()
{
int a;
char str1[20];
char str2[20];

cout<<"Enter an integer:\n";
cin>>a;
cin.ignore();
cout<<"Enter str1:\n";
cin.getline(str1,20,'\n');
cout<<"Enter str2:\n";
cin.getline(str2,20,'\n');
return 0;
}
It works as required. Thanks.
Topic archived. No new replies allowed.