首页 文章

查找istringstream中有多少个字符串

提问于
浏览
0

我想知道当我使用 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) .

3 回答

  • 2

    我知道的唯一方法是解析字符串以查看 . std::distance istream_iterator 可以为您做到这一点:

    std::distance(std::istream_iterator<string>(ss), 
                  std::istream_iterator<string>());
    
  • 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

    您可以执行类似的操作,添加while循环

    while(ss>>cadena) {

相关问题