0

My code to assess whether the command-line argument consists solely of digits compiles but doesn't work properly, and I can't figure out exactly what the problem is. Even if I enter an integer-only argument on the command-line, the program keeps outputting the message "Key must only include digits" (which is supposed to be the output only if non-digits are entered), instead of what I want it to output, which is "Key is valid." My code is below; any help would be greatly appreciated. Thank you.

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

int main (int argc, string key[])
{
    // confirm single command-line argument
    
if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    else
    {
        int keylength = strlen(key[1]);
        int i;

// check if each character in command-line variable "key" is a digit
        for (i=0; i <= keylength; i++)

                if (isdigit(key[1][i])==0)
                    {
                        printf("Key must only include digits.\n");
                        return 0;
                    }
    }
            printf("Key is valid.\n");
     return 0;
}
1

Ooh, a very subtle error! Look at the following:

for (i=0; i <= keylength; i++)

Say that the key is 48. Then keylength is 2. Now, if i starts at 0, what's the last value of i that will run a pass through the loop? It's 2, right?

Now, what is the char at key[1][2]????

Programming note. Best practice is to use the reserved variable name of argv, not key, to set up the program, as in (for now):

int main (int argc, string argv[])

You'll discover later that the correct form is this:

int main (int argc, char* argv[])

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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