First of all, start using std::string
s and std::getline
. Secondly, the reason for the trashing is that there's still a newline in the buffer. If you expect the user to be entering values one line at a time, you should use istream::ignore
to skip everything up to and including the next newline character. For example:
std::string s;
float f;
std::cin >> f;
std::cin.ignore(big_num, '\n');
std::getline(std::cin, s);
What big_num
should be depends on your expectations about the input. If you don't mind writing a lot and want to be on the safe side, use std::numeric_limits<std::streamsize>::max()
. If you do mind writing a lot, make a constant of the suitable type that you use everywhere.
For example, the above code will parse the following so that f = 5.0f
, s = Hello!
.
5
Hello!
However, it will parse the following exactly the same way:
5 Hi!
Hello!
If you want to preserve the Hi!
, you shouldn't ignore things, and instead define a proper grammar that you'll use to parse the document.