CS50替代-不输出密文-逻辑错误

时间:2020-06-22 16:25:22

标签: c cs50 substitution

该程序的功能将使用命令行参数来运行,例如,可以是字符串 NQXPOMAFTRHLZGECYJIUWSKDVB 。此26个字符的键意味着 A (字母的第一个字母)应转换为 N (键的第一个字符), B (字母的第二个字母)应转换为 Q (键的第二个字符),依此类推。然后,像 HELLO 这样的消息将被加密为 FOLLE ,根据密钥确定的映射替换每个字母。

例如

./ substitution JTREKYAVOGDXPSNCUIZLFBMWHQ

纯文本:HELLO

密文:VKXXN *

使用有效的命令行参数启动程序后,该程序不输出任何内容。它应输出已使用密钥加密的密文。我似乎找不到逻辑错误在哪里。

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

bool is_valid_key(string plaintext);

int main(int argc, string argv[])
{
    //Error message if user inputs incorret comand-line argument
    if (argc != 2)
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }
    if (!is_valid_key(argv[1]))
    {
        printf("Key must contain 26 characters.\n");
        return 1;
    }
    
    //Prompts user for plaintext
    string plaintext = get_string("Plaintext: ");
    string difference = argv[1];
    for (int i = 'A'; i < 'Z'; i++)
    {
        difference[i - 'A'] = toupper(difference[i - 'A']) - i;
    }
    printf("Ciphertext: ");
    for (int i = 0, len = strlen(plaintext); i < len; i++)
    {
        if(isalpha(plaintext[i]))
        {
            plaintext[i] = plaintext[i] + difference[plaintext[i] - (isupper(plaintext[i]) ? 'A' : 'a')];
        }
        printf("%c", plaintext[i]);
    }
    printf("\n");
}

//Checks vailidity of the key
bool is_valid_key(string plaintext)
{
    int len = strlen(plaintext);
    if (len != 26)
    {
        return false;
    }
    
    int freq[26] = { 0 };
    for (int i = 0; i < len; i++)
    {
        if (!isalpha(plaintext[i]))
        {
            return false;
        }
        int index = toupper(plaintext[i]) - 'A';
        if (freq[index] > 0)
        {
            return false;
        }
        freq[index]++;
    }
    
    return true;
}

1 个答案:

答案 0 :(得分:0)

第25行应为for (int i = 'A'; i <= 'Z'; i++)。 第29行应该是printf("ciphertext: ");