In: Computer Science
C Programing
How would i edit this code to have it return the cipher text.
void vigenereCipher(char* plainText, char* k){
int i;
char cipher;
int cipherValue;
int len = strlen(k);
//Loop through the length of the plain text string
for(i=0; i<strlen(plainText); i++){
//if the character is lowercase, where range is [97 -122]
if(islower(plainText[i]))
{
cipherValue = ( (int)plainText[i]-97 + (int)tolower(k[i % len])-97 ) % 26 +97;
cipher = (char)cipherValue;
}
else // Else it's upper case, where letter range is [65 - 90]
{
cipherValue = ( (int)plainText[i]-65 + (int)toupper(k[i % len])-65 ) % 26 +65;
cipher = (char)cipherValue;
}
//Print the ciphered character if it is alphanumeric (a letter)
if(isalpha(plainText[i]))
{
printf("%c", cipher);
}
else //if the character is not a letter then print the character (e.g. space)
{
printf("%c", plainText[i]);
}
}
}
Answer:
// change return type to char* as we need to return the cipher
text.
char* vigenereCipher(char* plainText, char* k)
{
int i;
char cipher;
int cipherValue;
int len = strlen(k);
char* cipherText =
(char*)malloc(sizeof(plainText)*sizeof(char));
//Loop through the length of the plain text string
for(i=0; i<strlen(plainText); i++)
{
//if the character is lowercase, where range is [97 -122]
if(islower(plainText[i]))
{
cipherValue = ( (int)plainText[i]-97 + (int)tolower(k[i % len])-97
) % 26 +97;
cipher = (char)cipherValue;
}
else // Else it's upper case, where letter range is [65 - 90]
{
cipherValue = ( (int)plainText[i]-65 + (int)toupper(k[i % len])-65
) % 26 +65;
cipher = (char)cipherValue;
}
//Print the ciphered character if it is alphanumeric (a
letter)
if(isalpha(plainText[i]))
{
// Assign the cipher to the cipherText instead of printing
it.
*cipherText = cipher;
cipherText++;
}
else //if the character is not a letter then print the character
(e.g. space)
{
// Assign the character to the cipherText instead of printing
it.
*cipherText = plainText[i];
cipherText++;
}
}
return cipherText;
}