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

c++ : check if it is a Number in class

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

在此代码中,我想知道两个数字是Int 还是字符串:

#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;
}

但是在运行代码之后,我只看到Nope!字符串,表示它是字符串。谁知道出了什么问题? 我用isdigit检查了数字,我只发送了两个数字

calulate.sum(3, 2);

但是什么都没有!! 谢谢

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

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

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(的范围内