in this code I want to know if two numbers are Int Or 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;
}
But after run code, I just see Nope! String , it mean it is string. who know what is wrong? I checked numbers with isdigit and I just sent two numbers
calulate.sum(3, 2);
but nothing!! thanks
Your issue is with your usage of std::isdigit(int)
The function is meant to check if a int
is equivalent to one of the 10 char
-represented decimal digits, 0123456789
. However, this function is only true for int
values of 48-57.
int
is expected to be the integer value of a char
. If you want it to resolve true
, use 48-57, where 48
is 0
, 49
is 1
, etc...
Note that your function would naturally resolve to true if you passed it a char
such as '3', like one commenter stated. This is because char(3) == int(51)
.
eg:
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
num1
and num2
are interpreted as characters by std::isdigit
. Typically this means ASCII characters .
And as an ASCII character 2 and 3 are control characters and not digits, which are in the range of '0' (0x30) to '9' (0x39)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.