delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/03/09/08:40:07

Message-Id: <2.2.32.19970309175606.00691f78@mailhost>
Mime-Version: 1.0
Date: Sun, 09 Mar 1997 15:56:06 -0200
To: djgpp AT delorie DOT com
From: Eyal Ben-David <eyalb AT aks DOT com>
Subject: Re: Flushing i/o stream?

At 11:02 PM 3/5/97 -0700, you wrote:
>     How can I flush an error from the console input stream (cin)?  How
>can I test if there is an error in the input stream?  I haven't been able
>to find the answer in the faq, with info or even examining "iostream.h". 
>I know it would be possible to overload the extraction operator, but this
>sort of program is designed for people with very little time per problem. 
>

Use diagnostic functions that come with iostream.

Examples: reading two ints
~~~~~~~~~
Method one: with operator !

        int  n1, n2;
        if (!(cin >> n1 >> n2))
            cerr << "error in input";

Method two: with good()

        int n1, n2;
        cin >> n1 >> n2;
        if (cin.good())
                // ...
        else
                cerr << "error in input";

please see also bad(), operator void*, fail() etc in iostream documentation.

Flushing istreams.
~~~~~~~~~~~~~~~~~~
For istream objects (cin also) there is no flush manipulator.
if you want to discard extra input use the member function 'ignore()'

example:
        if (!(cin >> n1 >> n2))
        {
            cerr << "......";
            cin.ignore(64, '\n');  // see docs about ignore
        }


Hope it helped you.

Eyal.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019