Home >Backend Development >C++ >Why Does `stringstream >>` Zero Out the Target Variable on Extraction Failure in C 11 and Later?

Why Does `stringstream >>` Zero Out the Target Variable on Extraction Failure in C 11 and Later?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-01 06:16:12716browse

Why Does `stringstream >>` Zero Out the Target Variable on Extraction Failure in C  11 and Later?
>` Zero Out the Target Variable on Extraction Failure in C 11 and Later? " />

Why Does stringstream >> Change the Value of Target on Failure?

In the quoted passage from Stroustrup's "TC PL, 3rd Edition," the author states that the value of v should remain unchanged if the extraction operation fails. However, an example contradicts this statement, as v gets zeroed out when the stringstream >> v operation fails.

Contradictory Behavior Explanation

The key to understanding this apparent contradiction lies in the different behavior of the extraction operator >> before and after C 11.

Before C 11

Prior to C 11, >> used a scanf-style parsing mechanism. When extraction failed, it left the value of v unchanged and set the failbit flag.

Since C 11

With C 11, >> switched to using the std::num_get facet for parsing input. As per the updated specification, if extraction fails:

  • For basic types like int, 0 is written to v and the failbit flag is set.
  • For types with overflow protection, such as std::numeric_limits::max() or std::numeric_limits::min() is written to v and the failbit flag is set.

Example Output Explanation

In the provided example:

  • The value of v is initially 123.
  • After attempting to read a word into v (which fails), the value of v is set to 0.
  • The stringstream's rdstate() indicates that the failbit is set, confirming the extraction failure.

This behavior is consistent with the updated behavior of >> introduced in C 11.

The above is the detailed content of Why Does `stringstream >>` Zero Out the Target Variable on Extraction Failure in C 11 and Later?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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