凯撒密码未通过check50清除,无法弄清原因

问题描述 投票:0回答:1

我编写了作业代码,并尽我所能。我可以传递除一个以外的所有Check50参数!帮帮我??验证是正确的,但是当我运行调试器时,它开始在加密部分出现问题。谢谢!

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main(int arg, string argv[])
{

//KEY VALIDATION
if (arg != 2) //checks to make sure that arg is 2 (for # of arguements)
{
    printf("Usage: ./caesar key\n");
    return 1;
}

else if  (arg == 2)
{ // checks key for validity
    for(int i = 0, len = strlen(argv[1]); i < len; i++)
    {
        if (!isdigit(argv[1][i]))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
    }
    //int key = atoi(argv[1]);
}
//ciphering


int key = atoi(argv[1]);
string plain = get_string("plaintext: ");
int len_plain = strlen(plain);
string cipher = plain;

 for (int x = 0; x < len_plain; x++)
        {
            if (plain[x] >= 'a' && plain[x] <= 'z')
            {
                cipher[x] = ((plain[x] + key)%122);
                if (cipher[x]<97)
                {
                    cipher[x] = cipher[x] + 96;
                }
            }
            else if (plain[x] >= 'A' && plain[x] <= 'Z')
            {
                cipher[x] = ((plain[x] + key)%90);
                if (cipher[x] < 65)
                {
                    cipher[x] = cipher[x] + 64;
                }
            }
            else
            {
                cipher[x] = plain[x];
            }
        }
    printf("ciphertext: %s\n", cipher);
}

我一直得到的check50结果是,

:) caesar.c exists.
:) caesar.c compiles.
:) encrypts "a" as "b" using 1 as key
:) encrypts "barfoo" as "yxocll" using 23 as key
:) encrypts "BARFOO" as "EDUIRR" using 3 as key
:) encrypts "BaRFoo" as "FeVJss" using 4 as key
***:( encrypts "barfoo" as "onesbb" using 65 as key
output not valid ASCII text
c cs50 caesar-cipher
1个回答
0
投票
printf("ciphertext: ");  
for (int x = 0, y = len_plain; x < y; x++)
    {
        //Use islower and isupper instead of typing so much words
        if islower(code[i])
        {
            printf("%c", (((code[i] + k) - 97) % 26) + 97);
        }
        else if isupper(code[i])
        {
            printf("%c", (((code[i] + k) - 65) % 26) + 65);
        }
        //If neither then just print it
        else
        {
            printf("%c", code[i]);
        }
    }
printf("\n")
© www.soinside.com 2019 - 2024. All rights reserved.