>` Zero Out My Variable on Extraction Failure in C 11? " />
Why Stringstream >> Changes Value of Target on Failure?
In modern C (C 11 onwards), the behavior of the >> operator for stringstream when an extraction fails has changed from the earlier versions. As per the C 11 standard, upon failure, the target variable is set to a default value (typically zero for integers), and the failbit flag is set.
Prior to C 11, the behavior was different. According to Stroustrup's quote from "TC PL, 3rd Edition," upon failure, the target variable should remain unchanged. However, the code example provided demonstrates a contradiction, where the target variable v is zeroed after a failed extraction attempt.
This apparent contradictory behavior can be explained by the fact that the snippet is being compiled under C 11 mode, which changes the behavior of the >> operator as follows:
In the example code, the stringstream contains a string that cannot be converted to an integer, resulting in a parsing failure. Under C 11 mode, this failure causes v to be set to 0, as observed in the output. The failbit flag is also set, as indicated by the "state: failbit" message.
This change in behavior was introduced with C 11 to ensure consistency in handling extraction failures for stream extractors. It aligns with the general principle that stream extractors should not modify the target variable (if possible) in the event of a failure.
The above is the detailed content of Why Does `stringstream >>` Zero Out My Variable on Extraction Failure in C 11?. For more information, please follow other related articles on the PHP Chinese website!