I have the following code:
int choice = 0;
char st1[N];
cout << "enter choice" <<endl;
cin >> choice;
cout << "enter sentence" << endl;
cin.get(st1, N-1);
when getting to cin.get line, no matter what the input is, it will read \0 char into st1[0] and that's it.
I assume it has something to do with the latest cin ( into choice variable ).
How do i "clean" cin buffer before getting new input from the user? if that's possible.
thanks
You could always try using
cin.sync()
.You might use ignore to drop the newline from the buffer (e.g. drop X characters before the newline as delimiter). Extraction and ignore stop when the delimiter is extracted.
e.g.
Also related: Why would we call cin.clear() and cin.ignore() after reading input?
Do a
getchar()
aftercin >> choice;
. This will consume the\n
from the input buffer.Since
choice
is of typeint
, the\n
is left over in the buffer and when the string input is taken, this\n
is encountered and it stops taking input there.