 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Helmut Jarausch Guest
|
Posted: Sat Nov 26, 2005 2:44 pm Post subject: what is a format error within istream ? |
|
|
Hi,
Several sources on the C++ library state, that the fail bit is set
when a format error occurs on input.
But if I input a (true) double constant like 2.3 to an int variable
I don't get the fail bit set. gcc-3.4.3 just sets the int variable
to 2. Is this a well defined action? (I'd prefer the fail bit set)
Here is an example
#include <iostream>
using std::cout; using std::endl;
#include <sstream>
using std::istringstream;
int main() {
int i=7;
istringstream Inp("2.3");
cout << "state before: " << Inp.rdstate() << endl;
Inp >> i;
if (Inp.fail()) cout << "input failedn";
cout << "state after : " << Inp.rdstate() << endl;
cout << "got " << i << endl;
}
Many thanks for your comment,
Helmut.
--
Helmut Jarausch
Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
James Kanze Guest
|
Posted: Sun Nov 27, 2005 4:00 am Post subject: Re: what is a format error within istream ? |
|
|
Helmut Jarausch wrote:
| Quote: | Several sources on the C++ library state, that the fail bit is
set when a format error occurs on input.
But if I input a (true) double constant like 2.3 to an int
variable I don't get the fail bit set. gcc-3.4.3 just sets the
int variable to 2. Is this a well defined action? (I'd prefer
the fail bit set)
|
The problem is that the input parser is looking for an integer,
not a floating point value, so it stops at the '.', not
including it as part of the input. The resulting string, "2",
can be parsed correctly as an int.
Note that the ".3" is NOT extracted from the stream, and will be
read by the next read. Typically, this will cause an error
downstream, since there are extra characters.
If you really need an immediate here, then you can check for the
'.' after reading the int, e.g.:
int result ;
input >> result ;
if ( input && input.peek() == '.' ) {
input.setstate( std::ios::failbit ) ;
}
--
James Kanze mailto: [email]james.kanze (AT) free (DOT) fr[/email]
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 pl. Pierre Sémard, 78210 St.-Cyr-l'École, France +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|