I've got it working nearly perfectly. It works if the text is in lowercase, but I see that it's not working quite right when using uppercase. In check50 it only fails with lowercase:
encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword
\ expected output, but not "CaQGoh\n"
It passes the uppercase text check, but I get the wrong characters in the first or second position. For example, for the key pi and the message "AAAAAA" I get it encrypted as "VOPIPI".
Any clues as to what's wrong with my code?
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char * argv[])
{
// Accepting only one argument
if (argc != 2)
{
printf("Only one argument!\n");
return 1;
}
else
{
// loop every char in the argument to check whether it is an alpabetic char or not
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
// check if one character is not alphabetic
if (! isalpha(argv[1][i]))
{
printf("Only letters!\n");
return 1;
}
}
}
//get message to be encrypted
string p = GetString();
for (int i = 0, n = strlen(p), k = 0; i < n; i++, k++)
{
// ensure looping of key
int j = k % strlen(argv[1]);
//char from message plus char from key wrap both in uppercase and lowcase
int letterlow = ((((p[i] - 97)) + ((argv[1][j]) - 97)) % 26) + 97;
int letterupp = ((((p[i] - 65)) + ((argv[1][j]) - 65)) % 26) + 65;
// check if the char is uppercase, lowercase or anything else, converts key char to ease calculation.
if (isupper(p[i]))
{
argv[1][j] = toupper(argv[1][j]);
printf("%c", letterupp);
}
else if (islower(p[i]))
{
argv[1][j] = tolower(argv[1][j]);
printf("%c", letterlow);
}
else
{
printf("%c", p[i]);
k--;
}
}
printf("\n");
return 0;
}