Mberu
Mberu

Reputation: 33

How can I get only one digit as an argument of the main function?

I have a problem with isdigit(). For an exercise, I need to pass only a numerical value to the main function. This means that I cannot pass "3 4 5" neither "hello". My code is properly working with these examples but it's not working with the value "2x" even though it's working with the value "x2".

This is the code:

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>


int main (int argc, string argv[])
{
    if ((argc == 2) && isdigit(*argv[1]))
    {
        printf("%s \n", argv[1]);
        printf("%i \n", argc);
    }
    else
    {
        printf("You have to use only one numeric value \n");
    }
}  

I tried to change if ((argc == 2) && isdigit(*argv[1])) into if ((argc == 2) && isdigit(argv[1])) but I keep getting Segmentation fault.

Could you please help me? Thanks a lot!

Upvotes: 0

Views: 220

Answers (1)

everclear
everclear

Reputation: 332

isdigit(int character) checks only one value. You can see that because you have to pass *argv[1] being the first character of the second element in argv. The first character of 2x is 2 so your program behaves as expected.

What you could do is get the length of the input using strlen(argv[1]) and then use a loop to check whether all characters in the string are digits. This however only works for decimal integers.

Upvotes: 1

Related Questions