unget () and putback ()

0

I have looked for some definitions and so far I know that unget() must return the last character and putback() can return others that are not the last one.

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

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

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

    
asked by anonymous 22.08.2016 / 21:48

1 answer

0

Friend, I also found these two members very confused, but when I understood them, I saw how powerful they are! Let la, or unget () returns only one character for the input buffer cin, that is if you use cin> > variable, the variable will acquire the last valid character, I do not remember if space counts think to stop before space!

The putback () is magical, a true perfection to filter data, use example 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 it will read all the numbers before the bar, works with strings and spaces, string and numbers ...

test best way to get your questions answered!

    
14.12.2016 / 18:54