Clearing and Resetting StringStream
In C , a stringstream is an input/output buffer associated with a string object. It allows for manipulation of strings using stream operations.
Problem Statement:
Consider the following code:
<code class="cpp">stringstream parser; parser << 5; short top = 0; parser >> top; parser.str(""); // Attempt to reset parser parser << 6; // Doesn't put 6 into parser short bottom = 0; parser >> bottom;</code>
The issue arises when attempting to reuse the stringstream after clearing its contents using parser.str("").
Solution:
To properly clear a stringstream, you need to perform two steps:
<code class="cpp">parser.str( std::string() ); parser.clear();</code>
Explanation:
The first >> operation reads the integer 5 from the stringstream and sets the eof bit because the end of the string has been reached. The subsequent attempt to read 6 fails because the eof bit is still set. By resetting the underlying string and clearing the flags, you restore the stream to its initial configuration and allow subsequent operations to succeed.
The above is the detailed content of How Do You Properly Clear and Reset a StringStream in C ?. For more information, please follow other related articles on the PHP Chinese website!