Kulten
Kulten

Reputation: 119

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?

Upvotes: 1

Views: 70

Answers (2)

Nir
Nir

Reputation: 1678

You can also use this if you like to keep the commas

#include <sstream>
#include <iostream>

using namespace std;

int main()
{
  stringstream ss;
  string st = "2,3,55,33,1124,34"; 
  std::string token;
  ss.str(st);

  while(getline(ss, token, ',')) {
    cout << token << endl;
  }    

  return 0;
}

Upvotes: 1

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

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;
}

Upvotes: 2

Related Questions