c++ 中的 stringstream 有助于从字符串中提取逗号分隔的整数,但不能使用向量提取 space 分隔的整数,为什么?

stringstream in c++ helps to extract comma separated integers from string but not space separated integers using vectors,why?

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main() {
string str;
getline(cin,str);
stringstream ss(str);
vector<int> arr;
while(!ss.eof()){
    int num;
    char ch;
    ss>>num>>ch;
    arr.push_back(num);
}
for(int i=0;i<arr.size();i++){
    cout<<arr.at(i)<<endl;
}
return 0;

}

我得到 1,2,3,4,5 的输出为 1个 2个 3个 4个 5个 但是对于 1 2 3 4 5 它是 1个 3个 5个 为什么? space 也是一个字符,所以它应该可以工作,还是我遗漏了什么? 谢谢你的帮助。

因为格式化输入操作跳过白色spaces。因此会发生以下情况:

ss >> num // reads integer 1
   >> ch; // skips whitespace after 1 and reads char '2'

在下一次迭代中:

ss >> num // skips whitespace after 2 and reads integer 3
   >> ch; // skips whitespace after 3 and reads char '4'

最后一次迭代:

ss >> num // skips whitespace after 4 and reads integer 5
   >> ch; // Encounters eof, nothing is read

不要阅读 space 分隔列表的字符。或者您可以使用 std::noskipws 来更改此行为。

提取运算符“>>”提供读取 space 分隔整数而不读取分隔符:

ss >> num; 

而不是额外阅读原始代码中的分隔符:

ss >> num >> ch;

因为对于标准流,skipws 标志是在初始化时设置的。 这使得阅读 space 分隔的整数更简单。

要使两个分隔符的工作方式相似,请添加

ss >> noskipws;

如以下代码所示:

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main () {
  string str;
  getline (cin, str);
  stringstream ss (str);
  ss >> noskipws;
  vector<int> arr;
  while (!ss.eof ()) {
    int num;
    char ch;
    ss >> num >> ch;
    arr.push_back (num);
  }
  for (int i = 0; i < arr.size (); i++) {
    cout << arr.at (i) << endl;
  }
  return 0;
}