Then after I input the integer, the output will be the integer. But it just terminates and I could never input the string. However if I rewrite the code as the following (I just switch the order), I could do both.
1 2 3 4 5 6 7 8 9 10 11 12
int main()
{
string str;
getline(cin, str);
cout << str << endl;
int a;
cin >> a;
cout << a << endl;
return 0;
}
Does anyone know the reason? Many thanks. My compiler is g++ in Ubuntu.
When you use cin to read in a value, it reads values from standard input until it hits either a space, tab, newline, linefeed or carriage return characters. In your case, cin reads the int value until it hits a newline, then it stops. Now when you use getline, since the next character left in the input buffer is a newline, getline will read the rest of the line consisting of just the newline character and it will stop. So you will notice when you print your string, it prints 2 lines one line will move from the current line where the int value entered was to the next and the next line will be an empty line because of the endl character after you print the string.
To fix this, after you read in your integer, do: cin.ignore();
This will (as the name suggests) ignore the newline character after the value and go to the next line if the newline character was the last character before the '\0' character.
1 2 3 4 5 6 7 8 9 10 11
int main() {
int a;
cin >> a;
cin.ignore();
cout << a << endl;
string str;
getline(cin, str);
cout << str << endl;
return 0;
}
The reason it works when you switch order is because getline reads and discards the newline character and places the line reader thingy on the next line for the next read to occur.