Search code examples
c++streamstringstream

Iterating through a string with sstream


Here is a piece of code:

#include <sstream>
#include <iostream>

using namespace std;

int main()
{
  stringstream ss;
  string st = "2,3,55,33,1124,34";
  int a;
  char ch;
  ss.str(st);
  while(ss >> a)
  {
    cout << a << endl;
    ss >> ch;
  }
  return 0;
}

It produces the output:

2
3
55
33
1124
34

But if I remove the line ss >> ch it produces the output: 2.

Why does it stop iterating through the string? And what difference does ss >> ch make?


Solution

  • What difference does ss >> ch make?

    ss >> ch takes a character from your stream an store it in your char ch variable.

    So here it removes each and every comma (,) from your string.


    Why does it stop iterating through the string without ss >> ch?

    Without this operation, your iteration stops because ss >> a fails, since it tries to store a comma inside a, an int variable.


    Note: If you replace your commas with spaces, you could get rid of ss >> ch, since a space is recognized as a separator.

    Example:

    #include <sstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      stringstream ss;
      string st = "2 3 55 33 1124 34";
      int a;
      ss.str(st);
      while (ss >> a)
        cout << a << endl;
      return 0;
    }