问题描述
我想知道是否可以有多个 while (cin>>(variable))
如下代码:
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 结尾)后,我无法为第二个向量输入第二组数字,程序立即终止.我怀疑第一个向量的第一个 cin 的 EOF 也被第二个向量的第二个 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.
有没有办法让上面的程序正确运行,即有不止一个 while (cin)?
Is there any way for the program above to run correctly i.e. having more than one while (cin)?
推荐答案
当你执行 while (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>>input)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!