You could use getline to read the whole line at once, then std::string at if you need the first char, or use an isstringstream
if you need the first number.
char char1;
std::string input;
getline(std::cin, input);
if (!std::cin.good()) {
// could not read a line from stdin, handle this condition
}
std::istringstream is(input);
is >> char1;
if (!is.good()) {
// input was empty or started with whitespace, handle that
}
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, is
will be !good()
so char1
will not have been set.
Alternatively, after you've checked that cin
is still good, you could simply:
if (input.empty()) {
// empty line entered, deal with this
}
char1 = input.at(0);
With that, if the string is non-empty, char1
will be set to the first char
if input
, whatever that is (including whitespace).
Note that:
is >> char1;
will only read the first char, not the first number (same with the input.at()
version). So if the input is 123 qze
, char1
will 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 an int
variable, and cast properly afterwards.