每当我在代码中使用(cin>>(var))时,iStream陷入错误状态

发布于 2025-01-25 15:56:53 字数 1043 浏览 3 评论 0原文

我要运行的代码如下。在第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<<" ";
}

https://godbolt.org/z/c54dgdgdgdwcq

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<<" ";
}

https://godbolt.org/z/c54dGdWcq

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋意浓 2025-02-01 15:56:53

语句cin&gt;&gt; n返回cin对象本身,将其放入中,而则做类似的事情

while(true){
   cin >> n;
   if(cin){ // equals to if(!cin.fail())
      // ... body of while
   }
   else break;
}

,是的,离开循环后, cin is in 失败>状态,因此任何子序列操作员&gt;&gt;在您调用 clear


相关: https:// https://en.cppreference.com/w/w/cpp/io/ ios_base/iostate

the statement cin>>n return the cin object itself, put it inside while does something like

while(true){
   cin >> n;
   if(cin){ // equals to if(!cin.fail())
      // ... body of while
   }
   else break;
}

so yes, after you leave the loop, cin is in fail state, thus any subsequence operator >> would not success until you call clear.


relevant: https://en.cppreference.com/w/cpp/io/ios_base/iostate

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文