Search code examples
ccs50caesar-cipher

Is there another way to check whether it's an integer in Caesar Cipher other than a for loop? CS50 pset2 Caesar Cipher


I'm trying to check whether argv[ 1 ] is an integer by looping through every character in argv[ 1 ] and putting them in isdigit(). Technically it works but not exactly the way I want it to.

Here's my code.

int main(int argc, string argv[])

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

Code

As you can see by looping through the string the program prints out a new line of response for each character. I'm wondering whether there's another way to validate the input and only print the response once?

$ ./caesar 20
Sucess
20
Sucess
20
$ 
$ ./caser xyz
bash: ./caser: No such file or directory
$ ./caesar 20
Sucess
20
Sucess
20
$ ./caesar xyz
Usage: ./caesar key
$ ./caesar 20x
Sucess
20x
Sucess
20x
Usage: ./caesar key
$ 

terminal


Solution

  • Because return exits the function, there’s no need to use an else after an if branch containing a return – if the if path is taken, nothing after the if keeps running.

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

    From that point it might be easier to see that it’s safe to move your success message after the loop, when all digits have been checked.

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