每当我在代码中使用(cin>>(var))时,iStream陷入错误状态
我要运行的代码如下。在第9行中,我试图使用进行多个输入,而(cin>> n)
方法。我给出的输入就像:
2 4 5 6 45 357 3 (ctrl+z)(ctrl+z)
在Windows中指示EOF。
然后,即使以为数字被添加到vector v1
中,istream
被卡在错误状态中,原因是我得到的输出:
error2 4 5 6 45 357 3.
我还可以确认istream被卡住了在错误状态原因中,如果我在此之后使用另一种cin
语句,则编译器会忽略它,直到我通过cin.clear()
函数清除流。
任何人都可以告诉我为什么会发生这种情况,以及如何防止流陷入错误状态。还是正常的事情,我必须在每次(cin>>(var))语句之后使用cin.clear()
?
#include <iostream>
#include <vector>
using std:: cin; using std:: cout; using std::endl;using std::vector;
int main(){
vector<int> v1;
int n;
cout<< "enter the list of numbers";
while(cin>>n){
v1.push_back(n);
}
if((cin>>n).fail()){cout<<"error";}
for (auto i: v1){
cout<< i<<" ";
}
The code i am trying to run is given below. Here in line 9 I am trying to take multiple inputs using the while(cin>>n)
method. The input I gave is like :
2 4 5 6 45 357 3 (ctrl+z)(ctrl+z)
to indicate EOF in windows.
Then, even thought the numbers get added into the vector v1
, the istream
is stuck into error state cause the output I get this :
error2 4 5 6 45 357 3.
And I can also confirm that istream is stuck in error state cause if I use another cin
statement after this, it gets ignored by the compiler until I clear the stream by cin.clear()
function.
Can anybody please tell me why does this happen and how can I prevent the stream getting into error state. or is it something normal and I must use cin.clear()
after every while(cin>>(var)) statement?
#include <iostream>
#include <vector>
using std:: cin; using std:: cout; using std::endl;using std::vector;
int main(){
vector<int> v1;
int n;
cout<< "enter the list of numbers";
while(cin>>n){
v1.push_back(n);
}
if((cin>>n).fail()){cout<<"error";}
for (auto i: v1){
cout<< i<<" ";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
语句
cin&gt;&gt; n
返回cin
对象本身,将其放入中,而则做类似的事情,是的,离开循环后,
cin
is in失败>状态
,因此任何子序列
操作员&gt;&gt;
在您调用clear
。相关: https:// https://en.cppreference.com/w/w/cpp/io/ ios_base/iostate
the statement
cin>>n
return thecin
object itself, put it insidewhile
does something likeso yes, after you leave the loop,
cin
is infail
state, thus any subsequenceoperator >>
would not success until you callclear
.relevant: https://en.cppreference.com/w/cpp/io/ios_base/iostate