Could anybody clear a little confusion I have about cin.unget()
function.
Please consider this piece of code:
void skip_to_int()
{
if (cin.fail()) { // we found something that wasn’t an integer
cin.clear(); // we’d like to look at the characters
for (char ch; cin>>ch; ) { // throw away non-digits
if (isdigit(ch) || ch=="-") {
cin.unget(); // put the digit back,
// so that we can read the number
return;
}
}
}
error("no input"); // eof or bad: give up
}
if cin.unget()
put the digit back into input stream to be read again, wouldn't I get cin>>ch
the same character to check conditions for again, and therefore get stuck in infinite loop?
Lets take a closer look at skip_to_int
if (cin.fail()) {
if the last input was bad
cin.clear();
clear the flags and look for the next good data
for (char ch; cin>>ch; ) {
get a character
if (isdigit(ch) || ch=="-") {
if character is a character we want
cin.unget();
put it back into the stream
return;
exit the function!!!
}
otherwise loop back around to get the next character
}
no more characters, exit the loop
}
error("no input");
Immediately following the unget
, the function returns, ending the loop along with the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With