0

I'm working on vigenere.c and have started with my caesar.c as a base. I'm getting some strange outputs and think that I may have made some simple errors which are stopping this from running correctly. I'd appreciate any tips on where I've gone wrong....

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

int main(int argc, string argv[])
{
    // store key as string and its length as an integer
    string key = argv[1];
    int keylength = strlen(key);

    // check that there is a key, exit the program if not
    if (argc != 2 || keylength == 0)
    {
        printf("Please try again with an alphabetical key.\n");
        return 1;
    }
    // check if each character in key is alphabetical
    for (int n = 0; n < keylength; n++)
    {
        if (!isalpha(key[n]))
        {
            printf("Please try again with an alphabetical key.\n");
            return 1;
        }
    }

    // store text as string and its length as an integer
    string plaintext = GetString();
    int length = strlen(plaintext);

    // cipher and print each letter of the plain text string
    for (int i = 0, j = 0; i < length; i++, j++)
    {   

            // wrap to the first letter of the key word if required
            if (j == keylength)
            {
                j = 0;
            }

            int k = key[j];

            // check for upper case letters and apply cipher   
            if (isupper(plaintext[i]))
            {
                printf("%c", (((plaintext[i] - 'A') + k) % 26) + 'A');
            }
            // check fo lower case letters an apply cipher
            else if (islower(plaintext[i]))
            {
                printf("%c", (((plaintext[i] - 'a') + k) % 26) + 'a');
            }
            // print other characters unchanged
            else
            {
                printf("%c", plaintext[i]);
            }

        printf("\n");
    }
    return 0;
}
1

I would recommend you checking the numeric values you get after applying the cipher, either with gdb or with printf, for each letter. I suspect you are getting values that fall outside the range of letters. As for the reason, if i'm not wrong, you substract a or A to the letters to get a valid value between 0 and 25, but it seems you are not doing it for k. I recommend you trying to get a value between 0 and 25 for k too and trying again.

3
  • Thanks, that wasn't the only problem but it put me on the right track. Thank you!
    – Topher
    Nov 1 '15 at 7:04
  • Happy to hear it, thanks for accepting the answer! Nov 1 '15 at 10:21
  • Thank pseudo-omnipotence! I've been stressing out about this problem since it was assigned, and it's all so clear now!
    – Jared
    Jan 28 '19 at 2:03

You must log in to answer this question.

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