时间:2019-03-17 标签:c++: check if it is a Number in class

标签 c++

在这段代码中我想知道两个数字是 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。但是,此函数仅适用于 int 值 48-57。

int 预计是 char 的整数值。如果您希望它解析 true,请使用 48-57,其中 48049 >1 等...

请注意,如果您向函数传递一个诸如“3”之类的char,那么您的函数自然会解析为 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

关于时间:2019-03-17 标签:c++: check if it is a Number in class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59653449/

相关文章:

c++ - C/C++ 中的非线程安全文件 I/O

c++ - 根据对象的成员函数排序

python - 用 cython 包装 C++ 类,让基本示例正常工作

c++ - 从 Mat 转换为 Matx33f

c++ - std::transform() 在函数参数中传递引用

C++ 什么时候使用哪个(标准)异常?

c++ - 如何在 C++ 中正确使用用户输入的参数

c++ - 尽管有线程,Qt GUI 仍挂起

c++ - 如何在 Boosts 的 brent_find_minima() 中传递一些常量?

c++ - VS2008中一个奇怪的双重计算