为什么会出现下面的程序输出
1 2 3 4 4 4
不是
1 2 3 4 5 6
对于提供的每个值?
#include <iostream>
#include <iterator>
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::vector<int> numbers;
std::stringstream ss;
ss << " 1 2";
std::istream_iterator<int> start{ss},end;
ss << " 3 4";
numbers.push_back(*start++);
numbers.push_back(*start++);
numbers.push_back(*start++);
ss << " 5 6";
numbers.push_back(*start++);
numbers.push_back(*start++);
numbers.push_back(*start++);
std::cout << "numbers read in:\n";
for (auto number : numbers) {
std::cout << number << " ";
}
std::cout << "\n";
}
最佳答案
它并不像您想象的那样做迭代器。它是 ss 在迭代器进行后失效的。初始字符串流包含 1 2 3 4
并且处于有效状态。但是被第三个迭代器取消引用无效,所以下一个操作ss << " 5 6"
失败。要解决此问题,请清除 stringstream 变量的标志:
//...
ss.clear();
ss << " 5 6";
//...
输出:
numbers read in:
1 2 3 4 5 6
关于c++ - std::istream_iterator 停止前进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36365227/