Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read stringstream with dynamic size?

I wanted to experiment with stringstream for an assignment, but I'm a little confused on how it works. I did a quick search but couldn't find anything that would answer my question.

Say I have a stream with a dynamic size, how would I know when to stop writing to the variable?

 string var = "2 ++ asdf 3 * c";
 stringstream ss;

 ss << var;

 while(ss){
  ss >> var;
  cout << var << endl;
 }

and my output would be:

2  
++  
asdf  
3  
*  
c  
c  

I'm not sure why I get that extra 'c' at the end, especially since _M_in_cur = 0x1001000d7 ""

like image 408
thomast.sang Avatar asked Sep 21 '10 03:09

thomast.sang


People also ask

How do I find the length of a stream string?

std::stringstream oss("Foo"); oss. seekg(0, ios::end); int size = oss. tellg(); Now, size will contain the size (in bytes) of the string.

How does a Stringstream work?

The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings. By treating the strings as streams we can perform extraction and insertion operation from/to string just like cin and cout streams.

How do you check if a Stringstream is empty?

myStream. rdbuf()->in_avail() can be used to get the count of available characters ready to be read in from a stringstream , you can use that to check if your stringstream is "empty." I'm assuming you're not actually trying to check for the value null .

What should I use for Stringstream?

A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.


1 Answers

You get the extra c at the end because you don't test whether the stream is still good after you perform the extraction:

while (ss)        // test if stream is good
{
    ss >> var;    // attempt extraction          <-- the stream state is set here
    cout << var;  // use result of extraction
}

You need to test the stream state between when you perform the extraction and when you use the result. Typically this is done by performing the extraction in the loop condition:

while (ss >> var) // attempt extraction then test if stream is good
{
    cout << var;  // use result of extraction
}
like image 123
James McNellis Avatar answered Oct 02 '22 19:10

James McNellis