【问题标题】:Iterating through a string with sstream使用 sstream 遍历字符串
【发布时间】:2018-09-12 12:56:07
【问题描述】:

这是一段代码:

#include <sstream>
#include <iostream>

using namespace std;

int main()
{
  stringstream ss;
  string st = "2,3,55,33,1124,34";
  int a;
  char ch;
  ss.str(st);
  while(ss >> a)
  {
    cout << a << endl;
    ss >> ch;
  }
  return 0;
}

它产生输出:

2
3
55
33
1124
34

但如果我删除ss &gt;&gt; ch 行,它会产生输出:2

为什么它停止遍历字符串? ss &gt;&gt; ch 有什么不同?

【问题讨论】:

    标签: c++ stream stringstream


    【解决方案1】:

    ss &gt;&gt; ch 有什么不同?

    ss &gt;&gt; ch 从您的流中获取一个字符并将其存储在您的 char ch 变量中。

    因此,它会从您的字符串中删除每个逗号 (,)。


    为什么没有ss &gt;&gt; ch就停止遍历字符串?

    如果没有此操作,您的迭代将停止,因为 ss &gt;&gt; a 失败,因为它试图在 a 中存储一个逗号,这是一个 int 变量。


    注意:如果将逗号替换为空格,则可以去掉 ss &gt;&gt; ch,因为空格被识别为分隔符。

    例子:

    #include <sstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      stringstream ss;
      string st = "2 3 55 33 1124 34";
      int a;
      ss.str(st);
      while (ss >> a)
        cout << a << endl;
      return 0;
    }
    

    【讨论】:

    • 为什么只有昏迷?
    • @weens 逗号不是整数,所以ss &gt;&gt; a 不会删除它们。 ss &gt;&gt; ch,虽然会删除每个字符
    • @weens 因为在您的情况下,字符串包含逗号。如果您用字母或任何其他非分隔符替换逗号,ss&gt;&gt;ch; 会将其存储在 ch 中,就像使用逗号一样。
    【解决方案2】:

    如果您想保留逗号,也可以使用它

    #include <sstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      stringstream ss;
      string st = "2,3,55,33,1124,34"; 
      std::string token;
      ss.str(st);
    
      while(getline(ss, token, ',')) {
        cout << token << endl;
      }    
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2010-11-17
      • 2013-09-26
      • 2011-08-27
      相关资源
      最近更新 更多