Considering the following:
char c;
cin >> c;
cin.unget();
Assuming the char input was successful, is unget guaranteed to be able to back up at least that one character? If I ask for, and successfully get a string, can I be guaranteed to be allowed to call unget all the way to the beginning of that string?
You are guaranteed to be able to
ungetat least 1 character. Any more than one is up to the implementation and circumstances, so you shouldn’t assume that you canungetmore than one.EDIT: Sorry I was thinking of libc’s
int unget(int ch, FILE *stream). Which the standard says:I will see if I can find exactly what is said about
basic_istream<>& unget()EDIT: OK, so here’s what the c++ standard says about
basic_istream<>& unget()(bolding added by me):So the important bit is that it calls
sungetc(), so let’s see what the standard says about that:I see nothing that explicitly states a limitation, so it’s worth a try. If I understand this correctly, it will adjust pointers in the backing stream buffer. So as long as there is enough “history” in the buffer, it should continue to succeed.
Unlike C, however, it seems that you are never guaranteed that it will work, but you will likely be able to putback more than one character.
So my advice is to not depend on putting back more than one character, and always check for failure.