可能有多个while(cin> input) [英] Possible to have multiple while (cin>>input)

查看:57
本文介绍了可能有多个while(cin> input)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有多个 while(cin>>(变量)),如以下代码所示:

I would like to know if it's possible to have multiple while (cin>>(variable)) as in the following code:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<int> v1, v2;
int input;

while (cin>>input)
v1.push_back(input);

while (cin>>input)
v2.push_back(input);

return 0;
}

我程序的逻辑是让用户定义两组int向量中的元素数量和每个元素的值.

The logic of my program is to let user define the number of elements and value of each element in two sets of int vectors.

但是,我意识到输入第一个向量的第一组数字(以EOF结尾)后,我无法输入第二个向量的第二组数字,程序立即终止.我怀疑EOF意味着第一个载体的第一个cin也被第二个载体的第二个cin处理.

However, I realized that after entering the first set of numbers for the first vector (ending with an EOF), I'm unable to enter the second set of numbers for the second vector and the program terminates promptly. I suspect that EOF meant for the first cin for the first vector was processed by the second cin for the second vector as well.

以上程序是否可以正常运行,即有一个以上的时间(cin)?

Is there any way for the program above to run correctly i.e. having more than one while (cin)?

推荐答案

在(cin>> input)期间执行时,实际上是在询问输入流 cin 生成整数,直到流变坏(即遇到EOF,蒸汽无法将用户输入转换为整数,或者可能还有另一个问题).

When you do while (cin>>input) you are effectively asking the input stream cin to produce integers until the stream has gone bad (i.e. an EOF was encountered, the steam was unable to convert the user's input to an integer, or maybe there was another problem).

在循环终止后,流的状态仍将处于导致其停止循环的任何状态.为了继续从 cin 读取直到遇到另一个EOF令牌,您需要首先清除eof失败位,这可以通过使用 cin.clear来完成(如πάνταῥεῖ指出).().但是,如果输入由于其他原因而失败(也许用户输入的是单词而不是数字),则应首先检查 cin 的状态.

After the loop terminates the state of the stream will still be in whatever state caused it to stop the loop. In order to continue reading from cin until another EOF token is encountered you will need to first clear the eof fail bit, this can be done (as πάντα ῥεῖ points out) by using cin.clear(). However, you should check the state of cin first, in case the input failed for another reason (perhaps the user entered a word instead of a number).

两个选项可能是:检查是否仅设置了eof位,或者只能取消设置eof位:

Two options might be: check that only the eof bit was set, or you can only unset the eof bit:

if (cin.eof())
{
    std::cout << "Yay, reached an EOF" << std::endl;
}

cin.clear(std::ios_base::eofbit);

这篇关于可能有多个while(cin&gt; input)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆