使用 sstream 遍历字符串

Iterating through a string with sstream

这是一段代码:

#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 >> ch 它会产生输出:2.

为什么它停止遍历字符串? ss >> ch 有什么区别?

What difference does ss >> ch make?

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

所以在这里它会从您的字符串中删除每个逗号 (,)。


Why does it stop iterating through the string without ss >> ch?

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


注意: 如果你用 spaces 替换你的逗号,你可以去掉 ss >> ch,因为 space 被识别作为分隔符。

示例:

#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;
}

如果你喜欢保留逗号也可以使用这个

#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;
}