2012-03-02 23 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) {

相關問題