I have test many cases and most of them are fine except the following one:
~/workspace/pset2/caesar/ $ ./caesar 2
plaintext: I love tea
ciphertext: K nqxg vgcB
Where does the extra letter "B" come from? And how to fix it? Thanks!
Here is my code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int ASCII_TO_ALPHABETICAL_UPPER = -65;
int ASCII_TO_ALPHABETICAL_LOWER = -97;
char shift_letter(char letter, int shift);
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Please enter an integer for the key.");
return 1;
}
// turn key into integer
int shift = atoi(argv[1]);
// get plaintext from user
printf("plaintext: ");
string plaintext = get_string();
// initiate ciphertext;
char ciphertext[strlen(plaintext) + 1];
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
char letter = plaintext[i];
if (isalpha(letter))
{
// shift letter
ciphertext[i] = shift_letter(letter, shift);
}
else
{
// not a letter, add to cyphertext directly
ciphertext[i] = letter;
}
}
// print cyphertext
printf("ciphertext: %s\n", ciphertext);
return 0;
}
char shift_letter(char letter, int shift)
{
if (isupper(letter))
{
// shift the uppercase letter
// convert ASCII to alphabetical index
int alphabetical_index = (int) letter + ASCII_TO_ALPHABETICAL_UPPER;
// get the shifted alphabetical index
int shifted_index = (alphabetical_index + shift) % 26;
// convert back to ASCII
int ascii_shifted_index = shifted_index - ASCII_TO_ALPHABETICAL_UPPER;
// return the shifted letter
return (char) ascii_shifted_index;
}
else
{
// shift the lowercase letter
int alphabetical_index = (int) letter + ASCII_TO_ALPHABETICAL_LOWER;
int shifted_index = (alphabetical_index + shift) % 26;
int ascii_shifted_index = shifted_index - ASCII_TO_ALPHABETICAL_LOWER;
return (char) ascii_shifted_index;
}
}
char ciphertext
with one more spot than is needed: after all, it needs the same amount of characters as plaintext, doesn't it? If the last letter is different everytime, it could be that it's just 0's and 1's stuck in your char[] that aren't overwritten because you never get to the (n+1)nth element of ciphertext. Let me know if removing the '+1' fromciphertext[strlen(plaintext)+1]
works!