2012-03-02 37 views
0

知道有多少串中有我的变量,当我使用istringstream找到我想要多少字符串在istringstream

string cadena; 
int num; 

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

例如,如果cadena是:"1 2 3 4",当我使用istringstream我想知道如何很多字符串在ss(在这种情况下是4)。

+0

好了,'stringstream'不是'VECTOR' ... – 2012-03-02 18:38:49

+1

哪个字符你认为是终止一个字符串,只有空格? – perreal 2012-03-02 18:39:00

+0

我使用istringstream,因为我不想计算数字之间的空格。 – EricJ 2012-03-02 18:39:42

回答

2

我知道的唯一方法是解析字符串出来看。 std::distanceistream_iterator可以为你做的:

std::distance(std::istream_iterator<string>(ss), 
       std::istream_iterator<string>()); 
+0

之后,当然,他正在读取流,并且必须重新创建它才能重新读取它。 – 2012-03-02 19:34:22

+0

@JamesKanze:是的 - 虽然这对于一个stringstream来说很简单。明显的选择是将数据读入矢量中,然后查找矢量的大小。 – 2012-03-02 19:50:24

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

这没有奏效,编译器不知道count_if – EricJ 2012-03-02 19:19:43

+0

那是因为它的名字是'std :: count_if'。 – 2012-03-02 19:32:02

+0

但当然,这并没有告诉你任何可能有多少领域。 – 2012-03-02 19:32:38

0

你可以不喜欢,添加while循环

while(ss>>cadena) {