Cs50凯撒检查50不合格

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

我正在做CS50课程中的凯撒练习,但失败了。

下面是代码。

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

int main(int argc, string argv[])
{
    if (argc == 2)
    {
        string key = argv[1];
        int l = strlen(key);
        for (int i = 0; i < l; i++)
        {
            // if key[i] is an alphabet character
            if (isalpha(key[i]) != 0)
            {
                printf("Usage: ./caesar key\n");
                return 1;
            }
        }

        //change charater to number
        int k = atoi(argv[1]);

        //print Plaintext
        string plaintext  = get_string("Plaintext: ");

        int n = strlen(plaintext);

        char ciphertext[n];

        //declare plaintext in ASCII
        int nplaintext[n];

        //Change plaintext to ASCII
        for (int i = 0; i < n; i++)
        {
            nplaintext[i] = (int)plaintext[i];
        }

        //Declare ASCII for ciphertext which we name "plusplaintext"
        int plusnplaintext[n];

        for (int i = 0; i < n; i++)
        {
            //if Capital
            if ((nplaintext[i] < 91) && (nplaintext[i] > 64))
            {
                plusnplaintext[i] = 65 + ((nplaintext[i] + k) - 65) % 26 ;
            }

            //if Lowercase
            else if ((nplaintext[i] < 123) && (nplaintext[i] > 96))
            {
                plusnplaintext[i] = 97 + ((nplaintext[i] + k) - 97) % 26 ;
            }

            //if not character a -> z and A -> Z
            else
            {
                plusnplaintext[i] = nplaintext[i];
            }
        }

        for (int i = 0; i < n; i++)
        {
            ciphertext[i] = (char)plusnplaintext[i];
        }

        printf("ciphertext: %s\n", ciphertext);

    }

    else
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
} 

这是Check50的输出。

:) caesar.c exists.

:) caesar.c compiles.

**:( encrypts "a" as "b" using 1 as key, output not valid ASCII text**

:) 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

**:( encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key, output not valid ASCII text**

:) handles lack of argv[1]

当我测试这段代码时, 有时它给出了正确的结果, 有时它给出了错误的结果... ...最后多了一些字符... ...

我怎样才能改正我的代码?

c cs50 caesar-cipher
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.