Home > database >  Why are digits and letters giving me the same result and how can I fix it?
Why are digits and letters giving me the same result and how can I fix it?

Time:10-16

I am trying to understand why both letters and digits are giving me the same results here. I have tried changing the code but I am not getting my desired results.

I want users to be prompted to enter a 2nd command argument of a digit and nothing else.

What can I fix in my code to do that?

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

bool is_valid(string verify);
int main(int argc, string argv[])
{
    //check whether the user input a valid comand line arguement
    if (!is_valid(argv[1]))
    {
        printf("try again: \n"); //re-prompt user if they didn't enter a digit
        return 1;
    }

    printf("true\n");

}

bool is_valid(string verify)
{
    char ch = verify[1];
   if (!isdigit(ch))
        {
            return 0; //return false
        }

    return 1; //return true
}

CodePudding user response:

Array indices start from zero.

If argv[1] is of string length 1, then argv[1][1] (aka, verify[1]) will always be the null-terminating byte. Providing this program a single argument of length 1 will always have is_valid returning false.

Use verify[0] to check the first character of the string. Alternatively, loop through each character of the string to check that they are all digits.

You should test that argv[1] is not NULL beforehand (argc >= 2).


An example program:

/* this program checks that its first argument contains only digits */
#include <ctype.h>
#include <stdio.h>

int is_valid(const char *);

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "usage: %s STRING\n", argv[0]);
        return 1;
    }

    if (is_valid(argv[1])) {
        puts("Valid!");
    } else {
        puts("Invalid!");
    }
}

int is_valid(const char *str)
{
    for (size_t i = 0; str[i] != '\0'; i  ) {
        if (!isdigit((unsigned char) str[i])) {
            return 0;
        }
    }

    return 1;
}
  • Related