1

I want to know how many strings there are in my variable when I use istringstream:

string cadena;
int num;

istringstream ss(cadena);
ss >> num;
int n = ss.size();  // This doesn't work

For example if cadena is: "1 2 3 4", when I use istringstream I want to know how many strings are in ss (in this case 4).

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
EricJ
  • 131
  • 3
  • 13

3 Answers3

2

The only way of which I'm aware is to parse the strings out to see. std::distance with an istream_iterator can do that for you:

std::distance(std::istream_iterator<string>(ss), 
              std::istream_iterator<string>());
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • After which, of course, he's read the stream, and has to create it again to reread it. – James Kanze Mar 02 '12 at 19:34
  • @JamesKanze: Yup -- though of course that's pretty easy to do with a stringstream. The obvious alternative would be to read the data into a vector, then find the size of the vector. – Jerry Coffin Mar 02 '12 at 19:50
1
#include <iostream>
#include <sstream>
#include <algorithm>
#include <ctype.h>

int  main()
{
  std::string str = ss.str();

  // int c = (int) std::count_if (str.begin(), str.end(), isspace) + 1;
  int c = 1;  // 0
  for (unsigned int i = 0; i <str.size(); i++ ) 
    if (isspace(str[i])) 
      c++;
  std::cout << c;
  return 1;
}
perreal
  • 94,503
  • 21
  • 155
  • 181
0

You can do something like, add while loop

while(ss>>cadena) {

Rajat Modi
  • 1,343
  • 14
  • 38
James
  • 1