Possible to have multiple while (cingt;gt;input)(可能有多个 while (cininput))
问题描述
我想知道是否可以有多个 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可能有多个 while (cin>>input)
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01