0

I had my Caesar all set and was moving on to Vig when I did one more check and realized that isdigit was only checking the first character. "[blank]", "aaa", "3 3" would all get kicked back and "44" would go though. Then I tried "a4" which got kicked back.... but "4a" did not, even though it should have been stopped. I tested out isalpha on the Vig set and I got the same thing (4a was stopped, a4 was not). I tried using a for loop to test each character individually but I couldn't get it to work.

First code: only validates 1st char

int main(int argc, string argv[])
{
    //Test if user number-only key in the command-line    
    if (argc == 2 && isdigit(*argv[1]))
    { ...

Code with FOR loop: wouldn't compile till I used the "!". Now rejects correct key.

int main(int argc, string argv[])
{
    //Test if user input a number-only key in the command-line
    for (int i = 0; i < strlen(argv[1]); i++)
    {
        if (!isdigit(argv[1][i]) && (argc == 2))
        {}
        else
        {        
            printf("Caesar key\n");
            return 1;
        }
    }

I've looked at other questions asking the same thing but I don't seem to be making the same mistakes as the others. Am I missing something?

0

First part makes sense, *argv[1] is same as *(argv[1] + 0) and argv[1][0] (array[index] is "syntactic sugar" for *(array + index)), referring to the first character.

You should definitely check for argc == 2 before doing the strlen(argv[1]), not inside the loop. If there's no argv[1], this might crash.

If you are going to use something like atoi later, there's nothing to do at that moment in case the character indeed is a digit, so move your usage instructions to the if part and remove the else. I don't know why it would enforce the ! at compile time (I guess you changed more than just that), but its placement makes sense logic-wise.

You mentioned "vig", meaning the Vigenère cipher, note that it is no longer part of pset2 in CS50x 2020.

You must log in to answer this question.

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