Boost logo

Boost :

From: Simon Buchan (simon_at_[hidden])
Date: 2005-10-18 21:03:07


Oliver Kullmann wrote:
> Hello,
>
> Consider the following basic task: Given an integer variable "n"
>
> int n;
>
> and an input stream "in"
>
> std::istream in;
>
> read an integer from in and put it into n. The "solution"
>
> in >> n;
>
> is not a solution, since according to 27.6.1.2.2 from the C++ standard
> the locale's num_get<> object is invoked, which according to
> 22.2.2.1.2 from the C++ standard invokes scanf from the C library,
Actually, it just says it should behave /like/ scanf: it is defined in
terms of it, not (necessarily) implemented with it.
> which then according to 7.19.6.2 from the C standard, clause 10,
> yields undefined behaviour if the number represented in the stream is not
> representable by the type int.
The standard specifies that when input fails (like a formatted input
operation not finding the right format), the stream's failbit is set, so
just:
in >> n;
if(in.fail()) {...}
does what you want. (The more general "if(!in)" works as well, also
including a corrupted stream and EOF)
>
> Thus, since "in" represents here user input, and user input shall never
> yield undefined behaviour, we cannot use "in >> n;".
I assume you mean "user input shall never yield *defined* behaviour" ;-)


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk