Problem while checking if a string is a number in c

Viewed 208

For a problem in CS50 class, I have to check if a key is valid, i.e if the input given by the user is a number. I tried different codes but every time, if there is at least one digit in the input, it returns that the key is correct. Though it should be correct only if all the characters of the string are digits...

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

int main(int argc, string argv[])
{
    if (argc !=2)
    {
        printf("Usage: %s key\n", argv[0]);
        return 1;    
    }
    else 
    {   
        for (int i = 0; i <= (strlen(argv[1])); i++)
        {
            if (isalpha(argv[1][i]))
            {
                printf("Usage: ./caesar key \n");
                return 1;
            }

            else
            {
                printf("%s\n", argv[1]);
                return 0;
            }
        }
    }
}

When the input is more than 2 strings, it should return 1 (that is working);

When the string [1] is not a number, it should return 1 (that is working too);

when the string [1] is a number, it should print the 2 strings (not working);

For example: I expect ./caesar 222f to return: Usage: ./caesar key, but the actual output is 222f

1 Answers

Your code only checks the first character of the string - It always returns a result based on whether or not the first character is or is not a digit.

Instead of printing the successful result within the loop, instead wait for the loop to iterate through all the characters, and only return early if a non-numeric character is found:

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

int main(int argc, string argv[])
{
    if (argc !=2)
    {
        printf("Usage: %s key\n", argv[0]);
        return 1;    
    }
    else 
    {   
        for (int i = 0; i <= (strlen(argv[1])); i++)
        {
            if (isalpha(argv[1][i]))
            {
                printf("Usage: ./caesar key \n");
                // Return early for badly formed argument
                return 1;
            }
        }

        // Now that all chars have been validated, print the argument
        printf("%s\n", argv[1]);
        return 0;
    }
}
Related