I make a lot of simple console c++ applications and one problem I am facing is the input buffer. I have tried cin.ignore and flush(), but they don’t seem to be working for me.
If I have code such as:
cin >> char1;
cin >> char2;
and I press: 1 (space) 2 (Enter), with just one enter, the 1 is stored to char1 and the 2 is stored to char2.
Sorry if I am a little fuzzy on what I am asking. I will try to edit this question if people don’t understand.
You could use getline to read the whole line at once, then std::string at if you need the first char, or use an
isstringstreamif you need the first number.Wrap that in a function if you do it often. With the above, if you hit enter directly (no characters entered), or if you enter data starting with whitespace,
iswill be!good()sochar1will not have been set.Alternatively, after you’ve checked that
cinis still good, you could simply:With that, if the string is non-empty,
char1will be set to the firstcharifinput, whatever that is (including whitespace).Note that:
will only read the first char, not the first number (same with the
input.at()version). So if the input is123 qze,char1will receive'1'(0x31 if ASCII), not the value 123. Not sure if that is what you want or not. If it’s not what you want, read to anintvariable, and cast properly afterwards.