This works:
Code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[100] = {0};
cout<<"Please enter some text: ";
cin.getline(str, 100);
cout<<"You entered: "<<str<<endl;
return 0;
}
This doesn't work:
Code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[50] = {0};
cout<<"Please enter a word: ";
cin>>str1;
cout<<"You entered: "<<str1<<endl;
char str2[100] = {0};
cout<<"Please enter some text: ";
cin.getline(str2, 100);
cout<<"You entered: "<<str2<<endl;
return 0;
}
Correcting the previous program to make it work:
Code:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[50] = {0};
cout<<"Please enter a word: ";
cin>>str1;
cout<<"You entered: "<<str1<<endl;
char str2[100] = {0};
cout<<"Please enter some text: ";
cin.ignore();
cin.getline(str2, 100);
cout<<"You entered: "<<str2<<endl;
return 0;
}
Explanation:
When you use a line like:
cin>>str1;
the program looks for some input to read from cin(cin represents input from the keyboard). Since cin starts off empty, there is no input to read, and the program must wait for the user to enter some input. After the user enters some input, say 'Bob', and hits return, the return causes a newline(\n) to be added to the input, so this is what's in cin:
Bob\n
The operation 'cin>>' is defined to stop reading input when it encounters whitespace(spaces, tabs, newlines), so 'Bob' is read from cin, and then cin>> stops reading input, leaving the trailing '\n' in cin. Any unread data in cin remains there and will be read during the next read operation.
Now, cin.getline() works differently than 'cin>>'. cin.getline() reads in input until after it reads in a \n whereupon it immediately stops. In the 2nd program above, when you subsequently use cin.getline() to read from cin, getline() does not have to wait for more user input since there is already input in cin that it can read, namely the remaining '\n' leftover from the previous user input. So, cin.getline() reads the \n and stops, and execution continues with the next line in the program--making it seem like cin.getline() was skipped.
Note that if the program used cin>> the second time it read from cin instead of cin.getline(), since cin>> is defined to skip all leading whitespace, cin>> would have skipped over the \n remaining in the input stream. Then, because cin would be unable to find any input it could read after the \n, cin>> would have to wait for the user to enter more input.
So, the lesson is: when you use both cin>> and cin.getline() in a program, you have to be aware that the operation 'cin>>' will leave a trailing \n remaining in cin, which will mess up a subsequent cin.getline(). You can solve that problem by using cin.ignore() to erase any previous input remaining in cin.