My code seems to be working but when I enter only one or few characters in my plaintext, my cyphertext returns weird characters... I had a look at my code and try couple of solutions and I can see that the issue is fixed when I remove the usage of strlen. Based on reading on internet, I understood that strlen could have brought rubbish data in my array but I can't find a solution to clean my arrays or to make strlen work better.
for example:
plaintext: a
ciphertext: b���
Thank you for any advice!
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
string key = argv[1];
//check if there is only one argument
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
//check if the string has only digit
for (int i = 0 ; i < strlen(key) ; i++)
{
if (key[i] < '0' || key[i] > '9')
{
printf("Usage: ./caesar key\n");
return 1;
}
}
int k = atoi(argv[1]);
printf("%i\n", k);
//Prompt for Plain text
string p = get_string("plaintext: ");
int lenp = strlen(p);
//Create ciphertext
char c[lenp];
for (int i = 0; i < lenp; i++)
{
int pn = (int) p[i];
//no change if character is not a letter
if (pn < 65 || pn > 122 || (pn > 90 && pn < 97))
{
c[i] = p[i];
}
// to keep uppercase
else if (pn >= 65 && pn <= 90)
{
pn = pn - 65;
int cn = ((pn + k) % 26) + 65 ;
c[i] = (char) cn;
}
//to keep lowercase
else
{
pn = pn - 97;
int cn = ((pn + k) % 26) + 97 ;
c[i] = (char) cn;
}
}
printf("ciphertext: %s\n", c);
return 0;
}