没有读取c++输入

C++ input not being read

本文关键字:输入 c++ 读取      更新时间:2023-10-16

我刚开始使用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的工作状态

以下是我的评论:

  1. fflush(stdin)无效。stdin无法刷新。同时,这可能与cin不同。
  2. 您需要在cin >> input之后检查cin.fail。如果我输入字母,你的输入语句将失败。