c++ - 在 while 循环中滥用 cin 进行 int 赋值

标签 c++ loops while-loop cin

只是尝试比较两个用户定义的 vector 以查看它们是否相等,当前代码:

vector<int> ivec1, ivec2; //vectors, uninitialized

int temp1;

cout << "Enter integers to be stored in ivec1." << endl;

while(cin >> temp1) //takes input from user and creates new element in the vector to store it
{
    ivec1.push_back(temp1);
}

int temp2;

cout << "Enter integers to be stored in ivec2." << endl;

while(cin >> temp2) //same as above with different vector
{
    ivec2.push_back(temp2);
}

if(ivec1 == ivec2)
    cout << "ivec1 and ivec2 are equal!" << endl;
else
    cout << "ivec1 and ivec2 are NOT equal!" << endl;

到目前为止,它让我可以很好地为 ivec1 赋值,但是当我通过输入一个字母使 cin 失败来退出 while 循环时,它会跳过第二个 while block 。出于好奇,我尝试在第一个 while 循环之后放入其他 cin 语句,它也会忽略它们。

强制 cin 失败是否会导致程序忽略对其的所有其他调用或其他问题,或者是否还有其他问题?如果是这样,我怎样才能让这个程序做我想做的事?

截图供您观赏: http://img695.imageshack.us/img695/2677/cinfailure.png

*PS。拥有 temp1 和 temp2 只是我试图弄清楚两个赋值循环使用相同的 int 是否会导致问题,无论如何我只是想把它留在那里

最佳答案

您必须执行cin.clear()来重置流状态。然后,您必须确保从流中读取有问题的字符(使用 here 中描述的技术之一),以便下一个输入操作也不会失败。

关于c++ - 在 while 循环中滥用 cin 进行 int 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6861060/

相关文章:

c - 通过键盘输入暂停 while 循环

c++ - 在 C++ 容器中一起使用所有子类的设计

c++ - 虚函数的 Vtable 是如何工作的

Java for 循环,同时将变量保持在一个范围内

r - 在 for 循环中提取数据并将其 append 到新数据集

scala - 优雅的 Iteratee -> 枚举器 "forwarding"正在运行

python - 在 for 循环中嵌套 for 循环,将每个循环打印到新文件

php - 将 csv 文件行的每一项放入变量中

c++ - Boost.Thread 3.0.0 中的重大变化

c++ - -DNDEBUG 通常来自哪里?