0

After spending many hours on caesar, I have restarted from nothing several times and think my program is able to correctly validated the key given by the user. The problem is that my validation only works correctly on single digit keys. I have converted the string into individual digits and then a for loop checks whether they are digits or not using isdigit(). Here is the code:

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

int main(int argc, string argv[])
{
    //check that a key was given
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    //check that the key is a number
    string s = argv[1];

    for (int i = 0, n = strlen(s); i < n; i++)
    {
        int check = isdigit(s[i]);
        if (check)
        // do the stuff    
        {
            printf("SUCCESS\n");
            printf("%s\n", argv[1]);
        }

        // invalid key
        else
        {
            printf("Usage: ./caesar key\n");
            return 1;  
        }
    }
}

When I run the program and give it an input like:

./caesar 4

Everything works great

With an input like:

./caesar 20x

I get the following output:

SUCCESS
20x
SUCCESS
20x
Usage: ./caesar key

I am hoping that this is a simple looping problem of some kind and that I don't have to start over again. Any help is much appreciated!

1 Answer 1

0

Looks good to me. You could simplify it by eliminating the check and s vars completely...

if(isdigit(argv[1][i]) ...

Now, all you need to do is take the entire string of digits stored at argv[1] and convert them to an actual number. Hint: atoi().

Remember to remove the extraneous diagnostic printf statements before final testing and submission.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .