0

I cannot figure out why I received this error. Only the word 'say' in the "world, say hello!" check50 is not ciphering correctly. My current code is below. Any advice will be greatly appreciated!

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

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Try again!\n");
        return 1;
    }

    string kw = argv[1];
    int nkw = strlen(kw);
    for (int pkw = 0; pkw < nkw; pkw++)
    {
        if (!isalpha (kw[pkw]))
        {
            printf("Try again!\n");
            return 1;
        }
    }

    for (int pkw = 0; pkw < nkw; pkw++)
    {
        if (islower (kw[pkw]))
        {
            kw[pkw] = kw[pkw] - 32;
        }
    }

    string s = GetString();
    int n = strlen(s);
    int pkw = 0;
    for (int p = 0; p < n; p++, pkw++) 
    {
        if (isalpha (s[p]))
        {
            if (isupper (s[p]))
            {
                s[p] = ((s[p] - 'A') + (kw[pkw % nkw] - 'A')) % 26 + 'A';
                printf("%c", s[p]);
            }

            if (islower (s[p]))
            {
                s[p] = ((s[p] - 'a') + (kw[pkw % nkw] - 'A')) % 26 + 'a';
                printf("%c", s[p]);
            }
        }    
        else
        {
            printf("%c", s[p]);
        }
    }
    printf("\n");
}
1

Common error. The code increments the indexes for both the key and the plain text for every character in the plain text string that is processed. The key index should only be incremented when a letter is encoded and not when a non-letter is processed. When the spaces and the comma in the plain text are printed, the index for the key is being incremented, putting it out of synch. Since there are 3 non-alphas in the plain text and 3 letters in the key, they come back into synch for the last word. That particular test was designed to check for this error.

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

1
  • Thanks Cliff! I'll try to fix that!
    – amanda
    Jul 5 '16 at 15:44

You must log in to answer this question.

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