c++:检查输入是否是数字

C++ : check whether an input is a number

本文关键字:是否是 数字 输入 检查 c++      更新时间:2023-10-16

我想让用户输入一个键,我想检查键是否是一个数字,如果不是,抛出一个消息,如果是0,退出。

我读到一个答案,建议下面的方法在这里:isdigit() c++,可能简单的问题,但卡住

int key;
while (true){
    cout << "Enter Key (Press 0 to Exit) : ";
    if (cin>>key){
        if (key == 0){ break; }
        //Code goes here
    }
    else{cout<<"Key should be a digit "<<endl;}
}

但是我的代码进入一个无限循环,只要我输入一个字母,我不知道为什么。

任何帮助将不胜感激,如果有更好的替代方法,那么请建议。

cin>>key

尝试从控制台读取int

如果你输入了一个非数字字符,下一次从cin读取将把cin流设置为错误状态,并且在清除流的错误标志之前不能再从cin中读取任何内容。

cin.clear();

重置错误状态。

您还必须忽略输入的字符,这会导致

的失败模式。
cin.ignore();

的例子:

int main()
{   
    int i;
    while (1) 
    {   
        std::cin >> i;
        if ( std::cin.fail())
        {   
            std::cout << "Something went wrong with cin" << std::endl;
            std::cin.clear();
            std::cin.ignore();
        }
        else
        {   
            std::cout << "input works, read: " << i << std::endl;
        }
    }
}

如果你想读一个单位数的控制台,也看这里:

从标准输入中捕获字符而不等待按回车

我的代码进入一个无限循环只要我输入一个字母

这是因为您将key声明为int,因此当std::cin无法读取整数时,流被设置为错误状态,并且if 's中的break语句不再可达。

一种可能的替代方法是从输入流中读取一行作为字符串,然后尝试将其转换为数字。

现在,给定OP的问题:

我想让用户输入一个密钥,我想检查密钥是否为

我不清楚(可能是我的错),如果必须被认为是一个单位数或多位数。在下面的代码片段中,我将展示后一种情况。请注意,它也可能包括前者。

#include <iostream>
#include <string>
int main()
{
    std::string line;
    while ( std::getline(std::cin, line) )
    {
        if ( line.empty() ) continue;
        try
        {
            int key = stoi(line);
            if ( !key ) break;
            // code that uses the key...
        }
        catch ( const std::invalid_argument &e )
        {
            std::cout << "Key should be a digit!n";
        }
        catch ( const std::out_of_range &e )
        {
            std::cout << "The value entered can't be represented by an int.n";
        }
    }
    return 0;
}