Use lstrip:

question.lstrip("-").isdigit()

Example:

>>>'-6'.lstrip('-')
'6'
>>>'-6'.lstrip('-').isdigit()
True

You can lstrip('+-') if you want to consider +6 a valid digit.

But I wouldn't use isdigit, you can try int(question), it'll throw an exception if the value cannot be represented as int:

try:
    int(question)
except ValueError:
    # not int
Answer from Maroun on Stack Overflow
๐ŸŒ
Unix.com
unix.com โ€บ applications โ€บ programming
C++ how to isdigit() a negative number? - Programming - Unix Linux Community
October 18, 2017 - hi people, I have a function which ... 2 + -3 the problem is that isdigit(in.peek()) is reading the '-' as a char and not part of the negative num......
Top answer
1 of 7
88

Use lstrip:

question.lstrip("-").isdigit()

Example:

>>>'-6'.lstrip('-')
'6'
>>>'-6'.lstrip('-').isdigit()
True

You can lstrip('+-') if you want to consider +6 a valid digit.

But I wouldn't use isdigit, you can try int(question), it'll throw an exception if the value cannot be represented as int:

try:
    int(question)
except ValueError:
    # not int
2 of 7
28

Use a try/except, if we cannot cast to an int it will set is_dig to False:

try:
    int(question)
    is_dig = True
except ValueError:
    is_dig = False
if is_dig:
  ......

Or make a function:

def is_digit(n):
    try:
        int(n)
        return True
    except ValueError:
        return  False

if is_digit(question):
   ....

Looking at your edit cast to int at the start,checking if the input is a digit and then casting is pointless, do it in one step:

while a < 10: 
     try:
        question = int(input("What is {} {} {} ?".format(n1,op,n2)))
     except ValueError:
        print("Invalid input")
        continue # if we are here we ask user for input again

    ans = opsop
    n1 = random.randint(1,9)
    n2 = random.randint(1,9)
    op = random.choice(list(ops))

    if question ==  ans:
        print ("Well done")
    else:
        print("Wrong answer")
    a += 1

Not sure what Z is doing at all but Z = Z + 0 is the same as not doing anything to Z at all 1 + 0 == 1

Using a function to take the input we can just use range:

def is_digit(n1,op,n2):
    while True:
        try:
            n = int(input("What is {} {} {} ?".format(n1,op,n2)))
            return n
        except ValueError:
            print("Invalid input")


for _ in range(a):
    question = is_digit(n1,op,n2) # will only return a value when we get legal input
    ans = opsop
    n1 = random.randint(1,9)
    n2 = random.randint(1,9)
    op = random.choice(list(ops))

    if question ==  ans:
        print ("Well done")
    else:
        print("Wrong answer")
Discussions

isdigit to work with negative numbers - Post.Byes - Bytes
Ok well i know that isdigit in my code is seeing the negatives as a character and so i made my program give an error message. But i need negative numbers to work how could i get this to work with negative numbers. The code is supposed to add the 3 numbers input into the command line argument ... More on post.bytes.com
๐ŸŒ post.bytes.com
July 28, 2012
C++ how to isdigit() a negative number?
hi people, I have a function which I am passing a stream which is basically postfix notation if(isdigit(in.peek())) { in >> number; nums.push(number); } else if (strchr("+-*/", in.peek( )) != NULL) { in >> symbol; do_operation(symbol, nums, okay); } else { in.ignore(); } the stream I am passing ... More on community.unix.com
๐ŸŒ community.unix.com
0
0
April 22, 2008
caesar - Unable to confirm user input is a number using isdigit in c - CS50 Stack Exchange
My code is attempting to; take user input from the command line; check if the input is a whole number; confirm positively if so; confirm negatively if not; however all numbers return a negative me... More on cs50.stackexchange.com
๐ŸŒ cs50.stackexchange.com
July 31, 2021
c++ - Is there an isdigit function (overload) which includes the negative symbol? - Stack Overflow
I'm trying to search for the beginning of a number. isdigit is there a c++ function that can include negatives in isdigit? So that it will match the first character of the number: "-13"? More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 188881 โ€บ is-there-a-way-to-use-isdigit-with-strings-that-could-contain-negative-numbers
Is there a way to use .isdigit() with strings that could contain negative numbers? | Sololearn: Learn to code for FREE!
January 26, 2017 - Would the best way to do this be to check for the "-" at the start of the string, strip it and then reapply it after the .isdigit() check? This seems a bit convoluted. ... use lstrip() function first. This will work for positive and negative numbers.
๐ŸŒ
Post.Byes
post.bytes.com โ€บ home โ€บ forum โ€บ topic
isdigit to work with negative numbers - Post.Byes - Bytes
July 28, 2012 - The code is supposed to add the 3 numbers input into the command line argument including negative numbers. ... #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> int main(int argc, char *argv[]){ int add=0; int i; int sum; if(argc == 4){ for(i=1; i<argc; i++){ ...
๐ŸŒ
Stack Exchange
cs50.stackexchange.com โ€บ questions โ€บ 41751 โ€บ unable-to-confirm-user-input-is-a-number-using-isdigit-in-c
caesar - Unable to confirm user input is a number using isdigit in c - CS50 Stack Exchange
July 31, 2021 - My code is attempting to; take user input from the command line; check if the input is a whole number; confirm positively if so; confirm negatively if not; however all numbers return a negative me...
๐ŸŒ
Vultr
docs.vultr.com โ€บ clang โ€บ standard-library โ€บ ctype-h โ€บ isdigit
C ctype.h isdigit() - Check if Digit Character | Vultr Docs
November 19, 2024 - Casting the character to unsigned char ensures that the isdigit() function exhibits defined behavior even if the input is a signed character with a negative value.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ can someone help me with this problem?
r/learnpython on Reddit: Can someone help me with this problem?
December 26, 2022 - If you want to avoid the user entering ... is negative. But you still have to remove the last quit() after else, otherwise it doesn't matter what you do, the program will quit even if the number entered is legal. The second part is going to need some work too but I think you're right on path! More replies More replies ... This is a guess, as Iโ€™ve never used โ€œisdigitโ€ before, but could it be that ...
Top answer
1 of 3
9

The trick is that the isdigit function does not take an argument of type char. Quoting the standard (N1570 7.4p1:

The header <ctype.h> declares several functions useful for classifying and mapping characters. In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.

The type char may be either signed or unsigned. If it's signed (as it very commonly is), then it can hold negative values -- and passing a negative value other than EOF (typically -1) to isdigit, or to any of the other functions declared in <ctype.h>, causes undefined behavior.

The solution is to convert the argument to unsigned char before passing it to isdigit:

char c = -46;
if (isdigit((unsigned char)c) {
    puts("It's a digit (?)");
}
else {
    puts("It's not a digit");
}

And yes, this is exactly as annoying and counterintuitive as you think it is.

2 of 3
3

The isdigit() function does not check if a number is a number, numbers are always numbers, it checks if the number is the ascii code of a character that corresponds to a numeric value or more precisely to a digit, i.e. a charachter of the following set

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

You can try to use strtol() for that purpose, like this

char *endptr;
char *number = "-46";

strtol(number, &endptr, 10);
if (*endptr == '\0') /* read the manual in the link to understand this please */
    printf("yes, it's a number!\n");
else
    printf("NO, `%s' is not a number!\n", number);

Note: if you read the manual or the standard specification of each function you use, you will improve your language skills, I very often see misuses of every single function from the standard library mostly because the user didn't read the manual.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ trouble understanding isdigit() function in c
r/learnprogramming on Reddit: Trouble Understanding isdigit() function in C
October 16, 2024 -

Original Question

I just started my first attempt at learning to program. I'm currently working through "Learn C Programming for the Absolute Beginner" and for the life of me I can't understand why this code does not work as expected:

//1. Build a number-guessing game that uses input validation (isdigit() function) to verify that the user has entered 
//   a digit and not a nondigit (letter). Store a random number between 1 and 10 into a variable each time the program 
//   is run. Prompt the user to guess a number between 1 and 10 and alert the user if he was correct or not.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>

int main() 
{
    int iRandomNum = 0;
    int iGuess = 0;

    srand(time(NULL));
    iRandomNum = (rand() % 10) + 1;

    printf("\nNumber Guessing Game, Chapter 3 Challenge");
    printf("\nGuess a number between 1 and 10: ");
    scanf("%d", &iGuess);
   
    if (isdigit(iGuess))
    {
        if ( iGuess > 0 && iGuess < 11)
        {
            printf("You guessed %d", iGuess);
            printf("The correct answer was %d", iRandomNum);

            if ( iGuess == iRandomNum)
            {
                printf("Congratulations! You guessed correctly!");
            }
            else
            {
                printf("Sorry! You guessed incorrectly...");
            }
            
        }
        else
        {
            printf("Invalid Response: You did not choose a number between 1 and 10");
            
        }
    }
    else
    {
        printf("\nInvalid Response: You did not select a number");
        
    }
    return 0;
}

No matter what my input, whether it is a number 1 - 10, or some other character, the code returns:

"Invalid Response : you did not select a number"

Edit:

All, thanks for your help. I understand now that isdigit only tests whether a single character is a digit.

To fix my code, (if isdigit returns true), I convert the character to a number like so:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>

int main() 
{
    int iRandomNum = 0;
    int iGuess = 0;
    char cResponse = '\0';

    srand(time(NULL));
    iRandomNum = (rand() % 10) + 1;

    printf("\nNumber Guessing Game, Chapter 3 Challenge");
    printf("\nGuess a number between 1 and 10: ");

    scanf("%c", &cResponse);

    if (isdigit(cResponse) == 0)
    {
        printf("\nInvalid Response, you did not input a number!");
    }   
    else 
    {
        //if iResponse is a digit, convert it to integer type by subtracting '0'
        iGuess = cResponse - '0';

        if ((iGuess < 1) || (iGuess > 10))
        {
            printf("\nInvalid Response: You did not choose a number between 1 and 10");
            printf("\nYou guessed %d", iGuess);
            printf("\nThe correct answer was %d", iRandomNum);  
        }
        else 
        {
            if ( iGuess == iRandomNum)
            {
                printf("\nCongratulations! You guessed correctly!");
            }
            else{
                printf("\nSorry! You guessed incorrectly...");
            }
        }        

    }
    return 0;
}

Edit 2:

Welp, looks like I still have some debugging to do, but that's another issue, unrelated to isdigit and more so catching a response that is longer than a single character. Not looking for help on that, just wanted to add this note in case someone tries to rely on this subpar codeblock for learning purposes. Back to it. Thanks again everyone.

Edit 3: (last one I promise)

Once again, I stand corrected. Isdigit does accept integers. As u/CodeTinkerer so kindly pointed out, I missed an explanation of isdigit posted by u/strcspn in an earlier reply on this thread. For the sake of correcting some misinformation in my post (above), here it is:

The function actually takes an int, but the value of that int is supposed to represent a character.

It's basically to allow passing in EOF, which can't be represented by unsigned char.

Hopefully, someone can take something useful away from my (mis)adventures in scanf().

๐ŸŒ
365 Data Science
365datascience.com โ€บ q&a โ€บ why str(-11).isdigit() is false โ€“ q&a hub
why str(-11).isdigit() is false โ€“ Q&A Hub โ€“ 365 Data Science
Also why does (-11).isdigit() returns False ? ... Hi Swarntam! Thanks for reaching out. The problem is, when you put negative numbers such as -11, the isdigit() method counts the - sign as a string value and it rejects it.
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ python
Beginner Python question - Python - The freeCodeCamp Forum
June 13, 2023 - iโ€™m new to python and i have ... but isdigit() canโ€™t identify negative numbers if iโ€™m correct? since a negative number would return as false, it defaults to the else statement that says to type a number next time. is ...
๐ŸŒ
Devcuriosity
devcuriosity.com โ€บ manual โ€บ details โ€บ python-isdigit-function
Python - isdigit() function with examples. Check string for digits.
bytearray_1 = bytearray(b"12345") ... characters (0-9) and returns True if all characters are digits. Case Sensitivity: Alphabetic characters, decimal points, and negative signs result in False....
๐ŸŒ
Linux Hint
linuxhint.com โ€บ isdigit-function-c-language
Isdigit() Function in C Language โ€“ Linux Hint
Getchar() may return EOF (which ... input stream has terminated. For the following expression, isdigit() returns a result of โ€œaโ€ equal to โ€œ0โ€ if โ€œbโ€ does not contain a character of โ€œdigitโ€ type....
๐ŸŒ
Quora
quora.com โ€บ What-method-checks-that-the-string-is-a-number-and-includes-negative-in-the-Python-language
What method checks that the string is a number and includes negative in the Python language? - Quora
That is simple check to find that typed input is a positive number it will return True if it is False if it is not but and also False if it is negative.Other built in method is isdigit() but also not accept negative number that consent you have ...