Topic: How should unget() work?


Author: francis@robinton.demon.co.uk (Francis Glassborow)
Date: Mon, 2 Jun 2003 01:03:46 +0000 (UTC)
Raw View
Look at the following source code:

#include <iostream>
#include <string>
using namespace std;

// clear out an input line
        inline void clear_input_line(std::istream & input){
                std::string garbage;
                input.unget(); // A
                std::getline(input, garbage);
        }



int main()
{
        int i;
        cout << "number: ";
        cin >> i;
        clear_input_line(cin); // B
        string message;
        cout << "number: ";
        getline(cin, message);
        cout << message;
    clear_input_line(cin); // C
        cout << "number: ";
        getline(cin, message);
        cout << message;

}

With the code as written and compiled with G++ 3.2 the call to
clear_input_line() at B waits for input even though there should be
residual input from the previous extraction (at least a newline) but it
behaves at C as I expect (i.e. no wait for input)

When the line marked as A is commented out the behaviour inverts, no
pause at B but a pause for input at C.

There is nothing wrong with that behaviour, it is exactly what I expect
and was my motive for inserting line A so that it would never wait for
input but would skip to a new line of input unless it was already at the
start of such a line.

1) Is operator>> not supposed to work with unget()?
2) Is unget() supposed to pause for input if there is no character to
push back.
3) How is it coping with pushing back a '\n' to an input buffer that is
currently terminated with a '\n' and then managing to extract both with
one call to getline()?

Is this a compiler bug? Or just my ignorance?

The more I dig the more I come to the belief that the way cin as
currently implemented is a serious wart blocking the understanding of
novices as well as many experienced programmers.

--
Francis Glassborow      ACCU
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]