Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input stream in C++. A little confusion with cin unget() function

Tags:

c++

cin

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?

like image 985
Ratkhan Avatar asked Dec 11 '19 02:12

Ratkhan


1 Answers

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.

like image 107
user4581301 Avatar answered Nov 17 '22 00:11

user4581301