>` Modify a Variable's Value on Extraction Failure? " />
Inconsistent Behavior of Stringstream >> on Value Modification on Failure
As stated by Stroustrup in TC PL, 3rd Edition, Section 21.3.3, a variable's value should remain unchanged upon an unsuccessful read operation. However, a peculiar behavior occurs when using stringstream >> with a non-matching data type.
In a code snippet presented, an integer variable v is initialized with 123. When attempting to read a word into this integer using stringstream >>, the value of v becomes zero despite the expected preservation of its original value.
This apparent contradiction is resolved by a clarification in the C 11 standard. Previously, upon a failed extraction, the value remained unchanged and the failbit was set. However, in C 11, a zero is now written to the variable, and the failbit is still set.
The cause of this altered behavior lies in the change from std::scanf-style input parsing to the usage of std::strtoll and similar functions in C 11. These functions handle numeric conversions in a different manner, resulting in the modification of v on extraction failure.
The above is the detailed content of Why Does `stringstream >>` Modify a Variable\'s Value on Extraction Failure?. For more information, please follow other related articles on the PHP Chinese website!