I have been trying to figure out what the issue is in my Caesar code. When I run check50, I see 2 errors -
encrypts "a" as "b" using 1 as key output not valid ASCII text
&
encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key output not valid ASCII text
Could someone please help? I could not figure out from the previous answers. Thank you very much!
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
//print message if argc count is not 2 & argv[1] is not present
if ((argc != 2) || (argv[1] == NULL))
{
printf("Usage: ./caesar key\n");
return 1;
}
string key = argv[1];
//check every letter of the argv[] string to see if that is a digit
for (int i = 0; i < strlen(key); i++)
{
if (!isdigit(key[i]))
{
printf("Usage: ./caesar key\n");
return 1;
}
}
int k = atoi(argv[1]);
//printf("key is %i\n", k);
string p = get_string("plaintext: ");
int plen = strlen(p);
char c[plen];
//Loop though plaintext to convert each character to secret character
for (int i = 0; i < strlen(p); i++)
{
if ((isalpha(p[i])) && (isupper(p[i])))
{
c[i] = (((p[i] - 'A') + k) % 26) + 'A';
}
else if ((isalpha(p[i])) && (islower(p[i])))
{
c[i] = (((p[i] - 'a')+ k) % 26) + 'a';
}
else
{
c[i] = p[i];
}
//printf("ciphertext: %s\n", c);
}
printf("ciphertext: %s", c);
printf("\n");
return 0;
}