当我输入一个字母时,cin输入(input是一个int),而不是一次回打印不正确,而是一次打印正确,然后在循环的其余部分使用inc [英] cin input (input is an int) when I input a letter, instead of printing back incorrect once, it prints correct once then inc for the rest of the loop

查看:206
本文介绍了当我输入一个字母时,cin输入(input是一个int),而不是一次回打印不正确,而是一次打印正确,然后在循环的其余部分使用inc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个乘法练习程序.就像我的标题所说的那样,如果我在控制台中输入字母而不是数字,它将在第一个字母上说正确,而在其他字母上说不正确.即使您没有触摸键盘,它仍然会吐出不正确的声音.

I'm making a multiplication practice program. As my title says, if I enter a letter into the console instead of a number, it will run off saying correct on the first one, but incorrect on the rest. Even if you're not touching the keyboard, it'll still spit out incorrect.

ans = table * i;
                    std::cout << table << " * " << i << " =" << std::endl;
                    std::cin >> input;
                    if(input == ans)
                    {
                            std::cout << "Correct! " << ans << std::endl;
                    }
                    else
                    {
                            std::cout << "Incorrect, the answer was " << ans << std::endl;
                            input = 0;
                            ans = 0;
                    }
            }

希望这能使您了解代码中正在发生的事情.这是输出.

Hopefully that gives you a view of what's happening in the code. Here's the output.

Enter the table you'd like to learn.
5
Enter the amount of multiples
3
5 * 0 =
s
Correct! 0
5 * 1 =
Incorrect, the answer was 5
5 * 2 =
Incorrect, the answer was 10
5 * 3 =
Incorrect, the answer was 15

我该怎么做才能解决此问题?感谢您的输入.

What could I do to fix this problem? Thanks for your input.

推荐答案

有很多方法可以构造各种测试,但是当使用cin(或通常使用任何输入函数)进行输入时,必须考虑输入缓冲区中任何未读的字符.使用cin,您必须满足以下三个条件:

There are a number of ways to structure the various test, but when taking input with cin (or generally with any input function), you must account for any characters in the input buffer that remain unread. With cin, you have three conditions you must validate:

    设置了
  1. .eof()(eofbit).或者到达输入的末尾,或者用户通过在windoze上按 Ctrl + d (或 Ctrl + z )手动生成EOF,但请参见:在Windows 10中,CTRL + Z不会生成EOF );

  1. .eof() (eofbit) is set. Either the end of input was reached, or the user manually generated an EOF by pressing Ctrl+d (or Ctrl+z on windoze, but see: CTRL+Z does not generate EOF in Windows 10);

.bad()(badbit).发生不可恢复的流错误;和

.bad() (badbit) is set. An unrecoverable stream error occurred; and

.fail()(failbit).发生匹配或其他可恢复的故障.发生故障时,输入停止,并且不再从输入缓冲区中提取任何字符.

.fail() (failbit) is set. A matching, or other recoverable, failure occurred. When the failure occurs input stops and no further characters are extracted from the input buffer.

(当输入结束时,您可以将1和2合并为一个测试)

(you can combine 1 & 2 into a single test as input is over at that point)

使用failbit,您必须做两件事. (1)您必须通过调用cin.clear()清除流错误状态,并且(2)您必须处理输入缓冲区中尚未读取的任何字符.通常,这可以通过包含<limits>并调用来解决:

With failbit, you must do two things. (1) you must clear the stream error state by calling cin.clear(), and (2) you must handle any characters that remain unread in the input buffer. Generally this is handled by including <limits> and calling:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

(将从输入缓冲区中清除最多INT_MAX个字符,遇到定界符(此处为'\n'时停止)

(which will clear up to INT_MAX characters from the input buffer, stopping when the delimiter ('\n' here) is encountered)

一个循环直到用户输入有效 integer 的简短示例可能是:

A short example that loops until a valid integer is input by the user could be:

#include <iostream>
#include <limits>

using namespace std;

int main (void) {

    int x = 0;

    while (1)       /* loop continually until valid input received */
    {
        cout << "\nenter an integer: ";
        if (! (cin >> x) ) {            /* check stream state */
            /* if eof() or bad() break read loop */
            if (cin.eof() || cin.bad()) {
                cerr << "(user canceled or unreconverable error)\n";
                return 1;
            }
            else if (cin.fail()) {      /* if failbit */
                cerr << "error: invalid input.\n";
                cin.clear();            /* clear failbit */
                /* extract any characters that remain unread */
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
            }
        }
        else {  /* on succesful read of int */
                /* extract any characters that remain unread */
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            break;  /* then break read loop */
        }
    }

    cout << "integer: " << x << '\n';
}

(如开头所述,只要涵盖所有三个条件,您就可以采用多种不同的方式来构造测试.)

(as mentioned at the beginning, you can structure the tests many different ways, as long as you cover all three conditions.)

此外,您可以通过调用rdstate()来显式检查流位,而不用例如.fail()等进行测试.

Additionally, you can check the stream bit explicitly by calling rdstate() instead of testing with .fail(), etc..., e.g.

if (std::cin.rdstate() == std::ios_base::failbit)

使用/输出示例

$ ./bin/cin_validate_int

enter an integer: no
error: invalid input.

enter an integer: "an integer"
error: invalid input.

enter an integer: abc 123
error: invalid input.

enter an integer: 123
integer: 123

仔细检查一下,如果还有其他问题,请告诉我.

Look things over and let me know if you have further questions.

这篇关于当我输入一个字母时,cin输入(input是一个int),而不是一次回打印不正确,而是一次打印正确,然后在循环的其余部分使用inc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆