#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
int n = atoi(argv[1]);
printf("plaintext: ");
string s = get_string();
printf("ciphertext: ");
for (int i = 0, j = strlen(s); i < j ; i++)
{
if (isalpha(s[i]))
{
if (isupper(s[i]))
{
printf("%c", ((('s[i]' - 65) + n) % 26) + 65);
}
else
{
printf("%c", ((('s[i]' - 97) + n) % 26) + 97);
}
}
}
}
else
{
printf("Error!\n");
return 1;
}
printf("\n");
return 0;
}
I am having difficulty with the part in the caesar cipher part where I have to convert the ascii index to alphabetical index. I spent a long time trying to figure out why the formula won't work. The code compiles and runs fine. But, if my key is 5, and I were to input "hello", then all I would get are five lots of v's ("vvvvv"). If I input "HELLO", I would get give lots of B's ("BBBBB").
It is most likely wrong, but here's is my understanding of it: taking "hello" for example, h would have ascii index of 104. Firstly, since i = 0
, we deal with "h", since it is a lower case, the following would run:
printf("%c", ((('s[i]' - 97) + n) % 26) + 97);
so, the int of s[i] would be 104, right? ((104-97)+5) % 26 = 12. Add back on the 97, I would get 109. printf the char of that should get me a lowercase m?
Could someone please correct me on my way of understanding this, and maybe provide a workaround for this. Thank you.