[LC++]IO in C++

Carlo Wood carlo at alinoe.com
Wed Nov 14 04:57:04 UTC 2001


On Tue, Nov 13, 2001 at 11:41:52AM -0500, Jack Lloyd wrote:
> Not necesarily better, but my usual strategy when I don't trust the user to
> do it right is read the entire line as a std::string, then parse and decode
> it myself, calling is*() as needed to verify the characters are valid. -J
> 
> > The best I have been able to come up with is:
> >
> > istringstream iss(myString); char tempChar;
> > if (!(iss>>verbosity)||(iss>>tempChar))
> >   cout<<"Error: myString is not an integer\n";
> >
> > Better solutions are welcome :-)

Yep, operator<< and operator>> are 'serializers': they provide
a hook (using the types ostream and istream for overloading)
to link buffers (streambuf) to objects.

Note that this isn't done character by character (you can't expect
to parse input character by character and abort the input, giving
an error or something similar) but per line.  In other words:

std::cin >> object1 >> object2 >> object3;

means that you decode one line by *expecting* first object1, then
object2 and then object3.  The one way to tell 'object2' that
the parsing of object2 went wrong is by setting the 'bad' bit
of cin (after which the parsing of object2 and 3 are garanteed
to fail as well).  It is not possible however to use that
for proper error handling (printing an error and startin over).

If you want to give feedback and try again, then you will have to
use 'try' (and throw exceptions inside the operator>> methods of
the objects on errors), catch these errors and act accordingly.

-- 
Carlo Wood <carlo at alinoe.com>



More information about the tuxCPProgramming mailing list