我将输出1,2,3,4,5作为1个2345但是对于1 2 3 4 51个35为什么?空格也是一个字符,因此它应该可以工作,或者我缺少某些东西吗?谢谢您的帮助。

问题描述 投票:0回答:2
##
#include 

#include

使用命名空间std; int main(){字符串str; getline(cin,str); stringstream ss(str);向量

arr; while(!ss.eof())...

c++ split integer extraction stringstream
2个回答
0
投票
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更改此行为。


0
投票
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; }

© www.soinside.com 2019 - 2024. All rights reserved.