Home > Backend Development > C++ > body text

Why Doesn\'t Resetting a Stringstream with `str(\'\')` Clear It?

DDD
Release: 2024-11-04 03:04:30
Original
929 people have browsed it

Why Doesn't Resetting a Stringstream with `str(

Clearing a Stringstream

The following code attempts to clear a stringstream object named parser:

<code class="cpp">stringstream parser;

parser << 5;
short top = 0;
parser >> top;
parser.str(""); // HERE I'M RESETTING parser

parser << 6; // DOESN'T PUT 6 INTO parser
short bottom = 0;
parser >> bottom;</code>
Copy after login

However, this approach doesn't work as expected. Let's explain why.

Problem:

The issue lies in the way stringstreams handle end-of-file (eof) and fail flags. When the first extraction (>> top) reaches the end of the string, it sets the eof bit. Subsequent operations on the stream fail because the eof bit remains set.

Solution:

To correctly clear a stringstream, both the underlying sequence and the fail and eof flags must be reset. The following code does this:

<code class="cpp">parser.str(std::string());
parser.clear();</code>
Copy after login

The str() method sets the underlying sequence to an empty string, while the clear() method clears the fail and eof flags.

With these changes, the code will correctly read the value 6 into the parser stream and store it in the bottom variable.

The above is the detailed content of Why Doesn\'t Resetting a Stringstream with `str(\'\')` Clear It?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!