[英]C++ input not being read
我刚开始使用c ++(来自Java),并且正在尝试进行一些基本练习。 想法是要求输入5以外的任何值,如果用户输入5,则显示一条消息,如果用户输入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
。 如果我输入字母,您的输入语句将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.