2

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

4
  • 1
    isdigit(2) is false. isdigit('2') is true. It's not clear to me what you are trying to do here, and how isdigitis relevant to that. Say, could you show an example where you expect your program to print "Nope! String"? Commented Jan 8, 2020 at 20:37
  • @IgorTandetnik I Just want to do a practice, it is a calculate with a class. for first numbers send from main to calculate.sum function , in this function I wanted to check inputs ( actualy in this code it is static but maybe I want to get numbers from user) from private function calculate.checkNumbers , show error if user send characters to program. Commented Jan 8, 2020 at 20:45
  • it was my mistake : calulate.sum('3', '2'); Commented Jan 8, 2020 at 20:46
  • @user2215032 -- What if the number of characters is more than one digit? Commented Jan 8, 2020 at 20:48

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.