user3720569 user3720569 - 3 months ago 45
C Question

stuck with the vigenere.c


I am stuck in this example. Whenever I put the keyword 'bacon' I get the wrong answer.
Any idea why this is happening? I can't find the bug and I have tried a lot.
Can you please help me?


When I run this:
./vigenere bacon
and input the text
Meet me at the park at eleven am
the answer should be
Negh zf av huf pcfx bt gzrwep oz
, but instead I get
Negh ne og tjs qaty bt syfvgb bm



Update: I made some changes as suggested by the comments but still having the same problem.


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

int main(int argc, char *argv[])
{
//check if it has only two values
if (argc != 2)
{
printf("Usage: ./vigenere keyword\n");
return 1;
}

// check that every letter of keyword is alphabetic
char *keyword = argv[1];
int keylen = strlen(keyword);
for (int i = 0, n = keylen; i < n; i++)
{
if(!isalpha(keyword[i]))
{
printf("alphabetic keyword only!!!\n");
return 1;
}

if(isalpha(keyword[i]))
{
// if a letter of keyword is uppercase
if (isupper(keyword[i]))
{
keyword[i] = keyword[i] - 'A';
}

// if a letter of keyword is lowercase
if (islower(keyword[i]))
{
keyword[i] = keyword[i] - 'a';
}
}
}

char *text = GetString();
for (int i = 0, n = strlen(text); i < n; i++)
{

if (isalpha(text[i]))
{
// if plaintext letter uppercase then...
if (isupper(text[i]))
{
text[i] = ((text[i] - 'A') + (keyword[i % keylen])) % 26 + 'A';
printf("%c",text[i]);

// ^^^^^^ ----> repeat the pattern
}

// if plaintext letter lowercase then ...
if (islower(text[i]))
{
text[i] = ((text[i] - 'a') + (keyword[i % keylen])) % 26 + 'a';
printf("%c",text[i]);

}
}

// if no letters in plaintext then ...
if (!isalpha(text[i]))
{
text[i] = text[i];
printf("%c",text[i]);
}
}
printf("\n");
}

Answer

So as @BLUEPIXY suggested I had to use a different variable in order to get the right answer:

   `char *text = GetString();
    int k = 0;
    for (int i = 0, n = strlen(text); i < n; i++)
    {    

    if (isalpha(text[i]))
    {
       // if plaintext letter uppercase
       if (isupper(text[i]))
       {
            text[i]= ((text[i] - 'A') + (keyword[k % keylen])) % 26 + 'A';
            printf("%c",text[i]);

                                        //^^^^^ ----> repeat the keyword pattern   
       }

            // if plaintext letter lowercase
       if (islower(text[i]))
        {
            text[i] = ((text[i] - 'a') + (keyword[k % keylen])) % 26 + 'a';
            printf("%c",text[i]);

        }
        k++;
     }`