【问题标题】:Find how many strings in istringstream查找 istringstream 中有多少个字符串
【发布时间】:2012-03-02 18:36:21
【问题描述】:

当我使用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)。

【问题讨论】:

  • 好吧,stringstream 不是 vector...
  • 您认为哪些字符可以终止字符串,只有空格?
  • 我使用 istringstream 是因为我不想计算数字之间的空格。
  • 不解压就不会知道。
  • 您为什么需要这些信息?如果您需要数值,只需在 std::vector< int > 的初始化程序中使用 std::istream_iterator<int>( ss ) 就可以了。

标签: c++ istringstream


【解决方案1】:

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

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

【讨论】:

  • 当然,在这之后,他读取了流,并且必须再次创建它才能重新读取它。
  • @JamesKanze:是的——当然,使用字符串流很容易做到这一点。显而易见的替代方法是将数据读入向量,然后找到向量的大小。
【解决方案2】:
#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;
}

【讨论】:

  • 那是因为它的名字是std::count_if
  • 当然,这并不能告诉您可能有多少字段。
  • 还是不认识这个功能。
  • 我们的想法是不使用循环,但我认为这是不可能的,谢谢 :)
【解决方案3】:

你可以做一些事情,添加while循环

while(ss&gt;&gt;cadena) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    相关资源
    最近更新 更多