Is it safe to use the value after a failed formatted extraction?
This is a relatively simple question, but I couldn't find a clear answer when I read 27.7.2.2.2 [istream.formatted.arithmetic] of the C ++ standard and got lost in all the faucet stuff.
If formatted checkout ( std::istream >> value
) fails, is it ok to use value
? Is the value always unchanged if the extraction fails? For example, is the following code legal and safe?
#include <iostream>
#include <sstream>
int main()
{
int value = 0;
std::stringstream ss("Hello world!");
ss >> value; // this will fail
// will value still be guaranteed to be zero?
std::cout << "value is " << value << std::endl;
}
While this works in practice , I want some kind of sponsor.
As a follow-up question, what about more complex data types, for example std::string
? Is it safe to use a string (and is its meaning known) if the extraction fails?
source to share
Brief investigation: On at least some compilers, the value is reset to the default in case of a non-empty input line and unmodified in the case of an empty input line , so there is istream
really no guarantee for the behavior .
source to share
In C ++ 03, the bad input was UB, due to the definition in terms of scanf-family (and UB meant you couldn't rely on an error message or, for example, a hexadecimal input with too many digits).
There was an obvious guarantee, but it was canceled by UB.
This was fixed in C ++ 11 using strtoll for example.
source to share