繁体   English   中英

C++:检查它是否是类中的数字

[英]c++ : check if it is a Number in class

在这段代码中,我想知道两个数字是 Int 还是 String :

#include <iostream>
using namespace std;

class calculate{
    private:
        bool checkNumbers(int num1, int num2){
            if(isdigit(num1) && isdigit(num2)){
                return true;
            }else{
                return false;
            }
        }

public:
    void sum(int x, int y){
        bool chek=checkNumbers(x, y);
        if(chek==true){
            cout<< "yes it is Number"<< endl;
        }else{
            cout<< "Nope! String"<<endl;
        }
    }
};

int main()
{
    calculate calulate;
    calulate.sum(3, 2);
    return 0;
}

但是在运行代码后,我只看到不! String ,这意味着它是字符串。 谁知道出了什么问题? 我用isdigit检查了数字,我只发送了两个数字

calulate.sum(3, 2);

但什么都没有!! 谢谢

您的问题在于您使用std::isdigit(int)

该函数旨在检查int是否等效于 10 个以char表示的十进制数字之一, 0123456789 但是,此函数仅适用于 48-57 的int值。

int应为char的整数值。 如果您希望它解析为true ,请使用 48-57,其中480491 ,等等...

请注意,如果您向函数传递了一个char例如“3”),则您的函数自然会解析为 true,就像一位评论者所说的那样。 这是因为char(3) == int(51)

例如:

isdigit('1'); // This is true, because '1' is a "char" digit
isdigit(49); // This is true

isdigit(1); // This is false
isdigit(60); // This is false

num1num2std::isdigit解释为字符。 通常这意味着ASCII 字符

并且作为 ASCII 字符 2 和 3 是控制字符而不是数字,它们的范围是 '0' (0x30) 到 '9' (0x39)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM