0

include

include

include

include

include

int main(int argc, string argv[]) { if (argc != 2) { printf("Usage: ./caesar key\n"); return 1; }

int k = strlen(argv[1]);

for (int i = 0; i < k; i++)
{

    if (!isalpha(argv[1][i]))
    {

       printf("Key must only contain alphabetic characters.\n");
       return 1;
    }
}

if (k!= 26)
{
    printf("Key must contain 26 characters.\n");
    return 1;
}

for (int j = 0; j < k; j++)
{
     for(int l = 0; l < k; l++)
     {
         if (argv[1][j] == argv[1][l] && l != j )
         {

             printf("Key must not contain repeated characters.\n");
             return 1;
         }
     }
}
string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int index=-1;
char result[25];

string p = get_string("Plain Text: "); printf("ciphertext: ");

for (int m = 0; m < strlen(p); m++)
{
    char temp = p[m];
    if (islower(temp))
    {
        temp = toupper(temp);
    }

    for (int alpha = 0; alpha < strlen(alphabets); alpha++)
    {
        if (temp == alphabets[alpha])
        {
            index = alpha;
        }
    }

    if (islower(p[m]))
    {
        result[m] = tolower(argv[1][index]);
    }
    else if (isupper(p[m]))
    {
        result[m] = toupper(argv[1][index]);
    }
    else {
        result[m] = p[m];
    }
}
printf("%s\n", result);
return 0;

}

// error is: encrypts "a" as "z" using ZYXWVUTSRQPONMLKJIHGFEDCBA as key output not valid ASCII text

0

So you set char result [25] to only hold 25 array values. If your plain text has more than 25 characters there will be a segmentation fault. If you create an int for the string length of the plain text and put it in your char result array it will fix your issue.

int h = strlen(text); char result [h];

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .