Paul KH Paul KH - 3 months ago 21
C Question

Vigenere fails check50 test encrypts “BaRFoo” as “CaQGon” using “BaZ” error in C

Vigenere fails check50 test encrypts "BaRFoo" as "CaQGon" using "BaZ" >error, my program output is "caQGoh".

I don't know what's the problem but i guess that this problem apears when there are different letter cases(lowercase and uppercase)plus the variance >is about 6 shifts.

//this is my code
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>


string getChars(string plaintext, string keyword)
{
int txtlen = strlen(plaintext);
int letter;
int j = 0;
for(int i = 0; i < txtlen; i++)
{
letter = plaintext[i];

// check if it's a letter

if (isalpha(letter))
{

// encrypt if letter
encryptChar(letter, keyword, j);
j++;
}
// if not just print it
else

{
printf("%c", letter);
}
}

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

char encryptChar(int letter, string keyword, int j)
{
int indexStart;
if (isupper(letter))
{
indexStart = 65;
}

else
{
indexStart = 97;
}

char encrypted;
int keyLen = strlen(keyword);
//I guess down here is my problem.

int LtrNum = 0;
if (isupper(letter))
{
LtrNum = keyword[j % keyLen] - 'A';
}
else if (islower(letter))
{
LtrNum = keyword[j % keyLen] - 'a';
}
LtrNum = (((letter - indexStart) + LtrNum) % 26);
encrypted = LtrNum + indexStart;

printf("%c", encrypted);

return 0;
}
int main(int argc, string argv[])
{
string keyword = argv[1];
string plaintext = GetString();

// pass the text and the keyword to encrypt
getChars(plaintext, keyword);

return 0;
}

Answer

Your problem is that the key itself is made of upper and lower case chars. SO it works well for BaR as this word has the same case as the key BaZ, but for Foo the last o is lower case and the key is upper so the computation LtrNum = keyword[j % keyLen] - 'a' is wrong.

I can suggest you to convert every char of the key to upper (for example) so that your code will looks like:

char encryptChar(int letter, string keyword, int j) {  
  int indexStart;  
  if (isupper(letter)) {  
    indexStart = 65;  
  }   
  else {  
      indexStart = 97;  
  }      
  char encrypted;  
  int keyLen = strlen(keyword);  
  int LtrNum = 0;  
  LtrNum = (((letter - indexStart) + (toupper(keyword[j%keyLen])-'A'))) % 26);  
  encrypted = LtrNum + indexStart;      
  printf("%c", encrypted);     
  return 0;  
}  
Comments