From Stroustrup's TC++PL, 3rd Edition, Section 21.3.3:
If we try to read into a variable v and the operation fails, the value of v should be unchanged (it is unchanged if v is one of the types handled by istream or ostream member functions).
The following example appears to contradict the above quote. Based on the above quote, I was expecting the value of v to remain unchanged -- but it gets zeroed. What's the explanation for this apparent contradictory behaviour?
#include <iostream>
#include <sstream>
int main( )
{
std::stringstream ss;
ss << "The quick brown fox.";
int v = 123;
std::cout << "Before: " << v << "\n";
if( ss >> v )
{
std::cout << "Strange -- was successful at reading a word into an int!\n";
}
std::cout << "After: " << v << "\n";
if( ss.rdstate() & std::stringstream::eofbit ) std::cout << "state: eofbit\n";
if( ss.rdstate() & std::stringstream::failbit ) std::cout << "state: failbit\n";
if( ss.rdstate() & std::stringstream::badbit ) std::cout << "state: badbit\n";
return 1;
}
The output I get using x86_64-w64-mingw32-g++.exe (rubenvb-4.7.2-release) 4.7.2 is:
Before: 123
After: 0
state: failbit
Thanks.
From this reference:
It seems that your compiler is compiling in C++11 mode, which changes the behavior.
The input operator uses the locale facet
std::num_get
whoseget
function invokesdo_get
. For C++11 it's specified to usestd::strtoll
et. al. type of functions. Before C++11 it apparently usedstd::scanf
style parsing (going by the reference, I don't have access to the C++03 specification) to extract the numbers. The change in behavior is due to this change in parsing the input.The operator >> is a formatted input operator.
As such is dependent on the locale for how input is read from the stream:
[istream.formatted.arithmetic]
As we can see above the value is actually set by the
numget
facet of the locale imbuded onto the stream.num_get virtual functions [facet.num.get.virtuals]
The definition of stage 3 changed drastically between n2723 -> n2798
Where do I find the current C or C++ standard documents?
num_get virtual functions [facet.num.get.virtuals]