【问题标题】:Caesar Cipher for CS50 [closed]CS50 的凯撒密码 [关闭]
【发布时间】:2014-03-27 06:30:27
【问题描述】:

我已经盯着这个问题看了好几个星期了,但我一无所获!它不起作用,我知道这么多,但我不知道为什么或出了什么问题。我确实知道开发人员对我突出显示的行吐出了“错误:预期的表达”,但实际上这只是冰山一角。如果有人知道如何解决这个问题,我将不胜感激!

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

int main(int argc, char *argv[]) 
{

    //Get the key
    if (argc != 2 || atoi(argv[1]) < 0)
    {
        printf("Usage: ./caesar k");
        return 1;
    }

    int key = atoi(argv[1]);
    string plaintex;
    string plaintext = GetString();

    for (int i = 0, n = strlen(plaintext); n < i; i++)
    {
        if (plaintext[i] > 'A' && plaintext[i] <= 'Z')
        {
            plaintext[i] = (plaintext[i] - 'A' + key) % 26 + 'A';
        }
    }  
    for (int i = 0, n = strlen(plaintext); n < i; i++)
    {           
        if (plaintext[i] >= 'A' && plaintext[i] >= 'Z')  // Highlighted line
        {
            plaintext[i] = (plaintext[i] - 'A' + key) % 26 + 'A';
        }
        else if (plaintext[i] >= 'a' && plaintext[i] < 'z')
        {
            plaintext[i] = (plaintext[i] - 'a' + key) % 26 + 'a';
        }
        else
        {
            printf("%c\n", plaintext[i]);
        }
    }
    return 0;
}

【问题讨论】:

标签: c encryption cs50 caesar-cipher


【解决方案1】:
if (plaintext[i] >= 'A' && plaintext[i] >= 'Z')

应该是

if (plaintext[i] >= 'A' && plaintext[i] <= 'Z')

【讨论】:

    【解决方案2】:

    A 的符号表索引没有Z 重要。最有可能A == 65 和Z == 90。

    if (plaintext[i] >= 'A' && plaintext[i] >= 'Z')
    

    您是在说“如果某物大于 65 并且也大于 90”。这个逻辑没有任何意义,这与说“如果某物大于 90”完全一样。

    你可能是说

    if (plaintext[i] >= 'A' && plaintext[i] <= 'Z')
    

    【讨论】:

    • 那会导致编译错误吗?听起来代码甚至都没有编译。
    • @DennisMeng 不应该,除非您已将编译器设置为将所有警告都转换为错误。 OP没有提到使用的编译器。
    • 我问是因为 OP 声称他的代码正在生成“错误:预期的表达式......”
    • 为了清楚起见,我会写'A' &lt;= x &amp;&amp; x &lt;= 'Z'。或者只使用字符分类宏,在本例中为isupper()
    • @vonbrand 请不要编辑帖子来更改它们的内容或含义,这很粗鲁,也完全违反了 SO 政策。你真的应该知道 3k rep。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 2020-05-31
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多