在 C 中进行替换时输出的额外字符和符号

Extra characters and symbols outputted when doing substitution in C

当我 运行 使用以下键的代码时,会输出额外的字符...

终端WINDOW: $ ./替换 abcdefghjklmnopqrsTUVWXYZI 明文:heTUXWVI ii ssTt 密文:heUVYXWJ jj ttUuh|

这是说明(cs50代换问题)

设计并实现一个替代程序,使用替代密码对消息进行加密。

在 ~/pset2/substitution 目录中名为 substitution.c 的文件中实现您的程序。 您的程序必须接受一个命令行参数,即用于替换的键。键本身应该不区分大小写,因此键中的任何字符是大写还是小写都不会影响程序的行为。 如果你的程序是在没有任何命令行参数或有多个命令行参数的情况下执行的,你的程序应该打印一条你选择的错误消息(使用 printf)和 return from main a value of 1(这倾向于表示错误)立即。 如果密钥无效(如不包含 26 个字符,包含任何非字母字符的字符,或不包含每个字母恰好一次),您的程序应该打印您选择的错误消息(使用 printf)和 return 立即从 main 中获取 1 的值。 您的程序必须输出明文:(没有换行符),然后提示用户输入一串明文(使用 get_string)。 您的程序必须输出密文:(没有换行符)后跟明文对应的密文,明文中的每个字母字符替换密文中的相应字符;非字母字符应原样输出。 您的程序必须保留大小写:大写字母必须保持大写字母;小写字母必须保持小写字母。 输出密文后,应该打印一个换行符。然后你的程序应该通过 returning 0 from main.

退出

我的代码:

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

int main(int argc,string argv[])
{
    char alpha[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    string key = argv[1];
    int totalchar = 0;

    for (char c ='a'; c <= 'z'; c++)
    {
        for (int i = 0; i < strlen(key); i++)
        {
            if (tolower(key[i]) == c)
            {
                totalchar++;
            }
        }
    }

    //accept only singular 26 key
    if (argc == 2 && totalchar == 26)
    {
        string plaint = get_string("plaintext: ");


        int textlength =strlen(plaint);
        char subchar[textlength];


        for (int i= 0; i< textlength; i++)
        {
            for (int j =0; j<26; j++)
            {
                // substitute

                if (tolower(plaint[i]) == alpha[j])
                {
                    subchar[i] = tolower(key[j]);

                    // keep plaintext's case
                    if (plaint[i] >= 'A' && plaint[i] <= 'Z')
                    {
                        subchar[i] = (toupper(key[j]));
                    }
                }

                // if isn't char
               if (!(isalpha(plaint[i])))
                {
                    subchar[i] = plaint[i];
                }
            }
        }

        printf("ciphertext: %s\n", subchar);
        return 0;
    }
    else
    {
        printf("invalid input\n");
        return 1;
    }



}

strcmp 比较两个字符串。 plaint[i]alpha[j] 是字符。可以与“常规”比较运算符进行比较,例如 ==.