#include#include
使用命名空间std; int main(){字符串str; getline(cin,str); stringstream ss(str);向量
arr; while(!ss.eof())...
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更改此行为。
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; }