先看下面的代码:
vector<int> intVtr;
intVtr.insert(intVtr.end(), istream_iterator<int>(cin), istream_iterator<int>());
上面的代码就是从标准输入中得到int型数字,并把值插入到intVtr中。当遇到非数字字符时,输入结束。
问题是,现在我要继续从标准输入读进int数字并插入intVtr结尾(也可以在其他位置,本文假定在结尾),那么该怎么写代码?开始的时候我习惯性的继续写:
//使用过intVtr之后
copy(istream_iterator<int>(cin), istream_iterator<int>(), inserter(intVtr, intVtr.end()));
编译运行时发现,这个copy根本不起作用,没有机会在标准输入中输入数字,这是为什么?搜索一下istream_iterator吧:在www.cplusplus.com里发现这么句话:
A special value for this iterator exists: the end-of-stream; When an iterator is set to this value has either reached the end of the stream (operator void* applied to the stream returns false) or has been constructed using its default constructor (without associating

本文探讨了在C++中使用cin输入时遇到的错误标记问题以及如何清空输入缓冲区。当遇到非数字字符时,istream_iterator会设置end-of-stream标志,导致后续输入无法进行。解决方案是通过cin.clear()清除错误标记,然后使用cin.sync()清空缓冲区,确保正常输入。同时,文章提到了cin.ignore()作为清空缓冲区的替代方法,但未深入研究。
最低0.47元/天 解锁文章
914





