0

(Learning C++) I have been looking at code portion below:

stringstream ss;

// more code 

ss.clear();
ss.str("");

Why is ss.str(""); called when ss.clear(); is meant to remove the string value? I printed out the str() value to std::cout and saw that it had length zero without the line ss.str(""); so why is it included?

In my research, I ran into this question and the accepted answer by @Johannes Schaub - litb does the same thing. What am I missing out.

heretoinfinity
  • 1,528
  • 3
  • 14
  • 33
  • 1
    https://stackoverflow.com/questions/20731/how-do-you-clear-a-stringstream-variable http://en.cppreference.com/w/cpp/io/basic_ios/clear – halfelf Jan 19 '18 at 03:37
  • `ss.clear()` doesn't do what you think it does, whereas `ss.str("")` does "clear" the stringstream buffer data. – Justin Randall Jan 19 '18 at 03:44

2 Answers2

4

std::stringstream::clear() is inherited from a parent class, and the inheritage source function is std::basic_ios::clear()

From CppReference (linked above):

Sets the stream error state flags by assigning them the value of state. By default, assigns std::ios_base::goodbit which has the effect of clearing all error state flags.

It does not clear the content of the stringstream, but all bad flags that were set in previous I/O operations (like encountering EOF).

The actual statement that clears the string content is ss.str("").

This example demonstrates what clear() does:

using std::cout;
std::istringstream s("8");
int a;
s >> a;
cout << a; // Output: 8
a = 10;
s >> a;
cout << a << " " << s.eof(); // Output: 10 1
s.clear();
cout << s.eof() << " " << s.str(); // Output: 0 8
iBug
  • 35,554
  • 7
  • 89
  • 134
0

Why is ss.str(""); called when ss.clear(); is meant to remove the string value?

clear() is not meant to remove the string value.It is meant to set the stream state flags.

stringstream ss;
ss<<1;
cout<<ss.str()<<endl; //prints 1
ss.clear();           // does not remove value from ss
cout<<ss.str()<<endl; //prints 1 
ss.str("");           //this removes the value
cout<<ss.str();       //empty
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34