Home > Backend Development > C++ > Why Does `stringstream >>` Modify a Variable\'s Value on Extraction Failure?

Why Does `stringstream >>` Modify a Variable\'s Value on Extraction Failure?

Barbara Streisand
Release: 2024-11-27 05:02:21
Original
460 people have browsed it

Why Does `stringstream >>` Modify a Variable's Value on Extraction Failure?
>` 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!

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