Definitions of unget() and putback()

Asked

Viewed 85 times

0

I looked for some definitions and so far what I know is that the unget() must return the last character and the putback() can return other than the last.

But my doubt would be on the functioning. I would like to know the practical uses, why it is used, it returns to where?

I did a test where I entered in a char, gave the unget() and then I used an input into another variable and I noticed that it filled itself with the returned character and I got a very superficial idea.

I would like you to explain to me this mechanics involving the buffer, the clean after an error and the questions in the second paragraph.

  • A common use is in lexical parsers - programs that convert a string of characters into a sequence of symbols (tokens). They are used in compilers and others parsers of files in text-based formats (XML, JSON, etc.). The return character operation to read it again allows you to use the input as a stack structure (get = pop, unget = push) rather than a simple sequence, simplifying some lexical algorithms.

1 answer

0

Friend also found very confusing these two members, but when I understood them, I saw how powerful they are! Come on, unget() returns only one character for the Cin input buffer, i.e., if you use Cin >> variable, the variable will get the last character valid, I don’t remember if space counts for before space!

Ja the putback() is magical, a true perfection to filter data, example of use on a date, you want to remove the day, month, year and store in variables, you could use this example.

int main(){
char ch;
int dia;
int mes;
int ano;

int contador_barras = 0;
while (cin){
    cin >> ch;
    switch (ch){
    case '\\': case '/':
        contador_barras++;
        break;
    case '0': case '1': case '2':case '3': case '4': case '5': case '6': case '7': case '8': case '9':
        if (contador_barras == 0)
        {
            cin.putback(ch);
            cin >> dia;
        }
        if (contador_barras == 1)
        {
            cin.putback(ch);
            cin >> mes;
        }else if (contador_barras == 2)
        {
            cin.putback(ch);
            cin >> ano;
        }
        break;
    case ';':
        cout << dia << " - " << mes << " - " << ano << endl;
        break;
    }
}

}

after using Cin.putback, I can use a Cin >> year that it will read all the numbers before the bar, works with strings and spaces, string and numbers...

Better test your doubts!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.