【问题标题】:stringstream in c++ helps to extract comma separated integers from string but not space separated integers using vectors,why?c ++中的stringstream有助于从字符串中提取逗号分隔的整数,但不能使用向量提取空格分隔的整数,为什么?
【发布时间】:2020-02-13 14:28:40
【问题描述】:
#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 为什么?空间也是一个字符,所以它应该可以工作还是我错过了什么? 谢谢你的帮助。

【问题讨论】:

  • 你有没有想过如果输入是1 2,为什么int a,b; cin&gt;&gt;a&gt;&gt;b; 有效?那个空间会发生什么?
  • while(!ss.eof()){ -- Don't do this

标签: c++ split integer extraction stringstream


【解决方案1】:

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

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

不要为空格分隔的列表读取该字符。或者您可以使用std::noskipws 来改变这种行为。

【讨论】:

    【解决方案2】:

    提取运算符“>>”通过以下方式提供读取空格分隔的整数而不读取分隔符:

    ss >> num; 
    

    而不是在原始代码中额外读取分隔符:

    ss >> num >> ch;
    

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-08-10
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多