Home > Backend Development > C++ > Why Does `stringstream >>` Zero Out My Variable on Extraction Failure in C 11?

Why Does `stringstream >>` Zero Out My Variable on Extraction Failure in C 11?

Patricia Arquette
Release: 2024-11-26 12:57:11
Original
647 people have browsed it

Why Does `stringstream >>` Zero Out My Variable on Extraction Failure in C  11?
>` 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:

  • If extraction fails due to an invalid data type (e.g., trying to read a word into an integer), the target variable remains unmodified, and the failbit flag is set.
  • If extraction fails due to value being too large or too small for the target type, the maximum or minimum possible value (e.g., std::numeric_limits::max() for integers) is written to the variable, and the failbit flag is set.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template