I'm doing caesar in pset 2 and it's working well when i enter ./caesar 1, or ./caesar a, or ./caesar 1 2, but when i try ./caesar 2h, it still runs the program. A couple of other people asked this question but none of the answers helped.Here's my code:

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

int main(int argc, string argv[])

    //stop if more than one key and if not a digit
    if (argc != 2 || isalpha(*argv[1]))
        printf("Usage: ./caesar key\n");
        return 1;

    int key = atoi(argv[argc - 1]);

    //ask user for string
    string ptxt = get_string("Plaintext:");

    //initialize the char ctxt to be as long as the string ptxt
    char ctxt [strlen(ptxt)];

    //run program, but keep uppercase/lowercase and non alphabetical characters
    for (int i = 0; i < strlen(ptxt); i++)
        if (isalpha(ptxt[i]))
            if (isupper(ptxt[i]))
                ctxt[i] = (((ptxt[i] - 65 + key) % 26) + 65);
            else if (islower(ptxt[i]))
                ctxt[i] = (((ptxt[i] - 97 + key) % 26) + 97);
            ctxt[i] = ptxt[i];

    //print the ciphertext
    printf("ciphertext: %s", ctxt);

    return 0; 

1 Answer 1


The code runs because it isn't validating that all of the chars in argv[1] are digits. The test in the code, isalpha(*argv[1]) actually takes the address of argv[1] as the location of a single char and checks it, but not the chars that follow.

You have to understand that isalpha() and all of its cousins only check one single char, not an entire string. If it tried to check a string, it would generate a seg fault.

So, since it's only checking one char, anything that starts with a digit passes. You need to run a loop across the entire string.

BTW, it's much simpler to use argv[1] than argv[argc - 1]

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

  • like what??????
    – Cliff B
    Commented Jul 29, 2020 at 0:41

You must log in to answer this question.

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