在这段代码中我想知道两个数字是 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,其中 48
是 0
,49
是 >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/