C++ 如何避免 int 变量的字符输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11523569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:13:23  来源:igfitidea点击:

How Can I avoid char input for an int variable?

c++integercharactercin

提问by Scoop

The program below shows a 'int' value being entered and being output at the same time. However, when I entered a character, it goes into an infinite loop displaying the previous 'int' value entered. How can I avoid a character being entered?

下面的程序显示了同时输入和输出的“int”值。但是,当我输入一个字符时,它会进入一个无限循环,显示之前输入的“int”值。如何避免输入字符?

#include<iostream>
using namespace std;

int main(){
int n;

while(n!=0){
            cin>>n;
            cout<<n<<endl;
           }
return 0;
}

回答by Anirudh Ramanathan

Reason for Infinite loop:

无限循环的原因:

cin goes into a failed state and that makes it ignore further calls to it, till the error flag and buffer are reset.

cin 进入失败状态,这使得它忽略对它的进一步调用,直到错误标志和缓冲区被重置。

cin.clear();
cin.ignore(100, '\n'); //100 --> asks cin to discard 100 characters from the input stream.

Check if input is numeric:

检查输入是否为数字:

In your code, even a non-int type gets cast to int anyway. There is no way to check if input is numeric, without taking input into a char array, and calling the isdigit()function on each digit.

在您的代码中,即使是非 int 类型也会被强制转换为 int。没有办法检查输入是否为数字,而不将输入输入到字符数组中,并isdigit()在每个数字上调用函数。

The function isdigit()can be used to tell digits and alphabets apart. This function is present in the <cctype>header.

函数isdigit()可用于区分数字和字母。此函数存在于<cctype>标题中。

An is_int() function would look like this.

is_int() 函数看起来像这样。

for(int i=0; char[i]!='
#include <iostream>
#include <climits> // for INT_MAX limits
using namespace std;
int main()
{
    int num;
    cout << "Enter a number.\n";
    cin >> num;
    // input validation
    while (cin.fail())
    {
        cin.clear(); // clear input buffer to restore cin to a usable state
        cin.ignore(INT_MAX, '\n'); // ignore last input
        cout << "You can only enter numbers.\n";
        cout << "Enter a number.\n";
        cin >> num;
    }
}
';i++){ if(!isdigit(str[i])) return false; } return true;

回答by user1480872

If you want use user define function you can use the ascii/ansi value to restrict the char input.

如果您想使用用户定义函数,您可以使用 ascii/ansi 值来限制字符输入。

48 -57 is the range of the 0 to 9 values

48 -57 是 0 到 9 值的范围

回答by Ryan Hallberg

##代码##