没有读取c++输入
C++ input not being read
我刚开始使用c++(来自java),我正在尝试做一些基本的练习。其思想是请求除5以外的任何输入,如果用户输入5,则显示一条消息,如果用户输入10次除5以外的任何输入,则显示另一条消息。下面是代码:
void notFive () {
int count = 0;
while (count < 10) {
int input = 0;
cout << "Enter any number other than 5." << endl;
cin >> input;
if (input == 5)
break;
count++;
}
if (count == 10)
cout<<"You are more patient than I am, you win.";
else
cout << "You weren't supposed to enter 5!";
}
}
我的问题是所有这些代码所做的就是打印出"输入除5以外的任何数字"。10次,然后说"你比我更有耐心,你赢了。"你知道哪里不对吗?
如果你们想要我所有的代码(确保我不是白痴),在这里:
#include <iostream>
#include <stdio.h>
using namespace std;
class Hello {
public:
void notFive () {
int count = 0;
while (count < 10) {
int input = 0;
cout << "Enter any number other than 5." << endl;
if ( ! (cin >> input) ) {
cout << "std::cin is in a bad state! Aborting!" << endl;
return;
}
if (input == 5)
break;
count++;
}
if (count == 10)
cout<<"You are more patient than I am, you win.";
else
cout << "You weren't supposed to enter 5!";
}
}hello;
int main() {
Hello h;
h.notFive();
return 0;
}
当我将notFive
更改为main
时,您的代码对我来说是完美的(在Visual Studio 2012中)。您的问题必须在此代码之外(可能是因为cin
处于破碎状态,正如其他人所建议的)。
改变这一行:
cin >> input
:
if ( ! (cin >> input) ) {
cout << "std::cin is in a bad state! Aborting!" << endl;
return;
}
您所描述的行为是如果在此代码运行之前cin
发生了坏的将会发生的情况。
将相同的代码添加到cin
的早期使用中,以找出它在哪里进入坏状态。
发生这种情况的一个例子是,如果代码试图读取int
,而用户输入了字母表中的一个字母。
您也可以调用cin.clear();
来恢复cin
的工作状态
以下是我的评论:
-
fflush(stdin)
无效。stdin
无法刷新。同时,这可能与cin
不同。 - 您需要在
cin >> input
之后检查cin.fail
。如果我输入字母,你的输入语句将失败。
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type