0

I don't really know what went wrong here.

I'm trying to test if the second word of the command line contain all digit. So I tried to check every character in argv[1] with the isdigit function by incrementing the i of argv[1][i].

So I was hoping by using !isdigit(argv[1][i]) I could check every character in argv[1]: argv[1][0], argv[1][1], argv[1][2]...until the end of argv[1]

But when I entered ./caesar 20x to test the code, it still gives back "plaintext:" when the output should be the error message "Usage: ./caesar key\n", because the third character is not a digit.

I posted the same question on cs section of stackoverflow, and I was told that the program is only checking the first character of argv[1], but code in the answers did not help

How can I fix this error?

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

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 if (isdigit(argv[1][i]))
        {
            string s = get_string("plaintext: ");
            return 0;
        }
    }
    }

}

1 Answer 1

1

They are right, your program is only checking the first character of argv[1].

Try to think - your for loop checks the first character; if its not a digit, it throws an error and ends the program. Or if its a digit, it prompts for input. So basically you are stopping the program either way just after checking the first character! What you should do instead, is keep looping till there are digits and stop the program only when an other character is encountered. If the loop ends without any error, only then you prompt for plaintext.

I could correct the code, but it would go against the course's honor code.

1

You must log in to answer this question.

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