I am having trouble with getting the right output. When I use debug, it steps through, but gives me the wrong character... but I've gone through my equation dozens of times even with pen and pencil and I'm still missing something. It also gives a segmentation fault if I just try to run it outright... I have a feeling the two issues are connected. I don't want an outright answer, but can someone point me in the right direction? ((edited per academic policy))

    //get test input from user and create a string out of it
    string input = get_string("plaintext: ");
    string key = argv[1];
    int leninput = strlen(input);

    //an exlamation point means the opposite of the function. So in this case, if it's NOT alpha.
    if (!isalpha(argv[1]))
        return 1;
    printf("ciphertext: ");
    //incrementing up the numbers in the input based on the string length of the user input
    for (int i = 0; i < leninput; i++)
        if (isalpha (input[i]))
            //counting up the counter for the key within alpha since we don't want to increment this value on
            //anything but an alphabetical character.
            for (int kcount = 0; kcount < strlen(key); kcount++)
                //take the input, minus 65, or A to avoid magic numbers to get to alphabetical index,
                //plus the different that using the key will add (while accounting for key's length and making it cycle around)
                // then modulus 26, plus 65 to get back to ascii.
                if (isupper(input[i]))
                    //since i can't pass the key value counter as a variable, we'll have to do it here.
                    printf("%c", (((input[i] - 'A') + (key[i % strlen(key)] - 'A') % 26) + 'A'));
                //this one does the same for lowercase characters with the difference being 97.
                if (islower(input[i]))
                    printf("%c", (((input[i] - 'a') + (key[i % strlen(key)] - 'a') % 26) + 'a'));

1 Answer 1


Your code assumes that if the plaintext is uppercase, the key will also be. That's not a valid assumption. Also, what might happen if the key is 'A' and you subtract 'a'?

Also, you are looping over the plaintext, but then you have a nested loop that loops over the length of the key. Can you see why that shouldn't work? If the plaintext is "aa" and the key is "bbbb" you would end up printing "bbbbbbbb".

  • Thank you! That helped a lot.
    – stephanie
    Apr 19, 2018 at 18:28

You must log in to answer this question.

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