You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Caesar加密未返回预期值,求密钥校验及代码bug排查帮助

CS50 Caesar任务:加密bug修复与密钥验证实现

一、加密结果不符合预期的修复

你的rotate函数存在数组越界问题,导致字符转换错误。当location + key%26的结果超过25时(比如原字符是'z'(location=25),key%26=1,总和为26),访问lower[26]会超出数组范围(数组索引仅到25),从而返回随机错误值。

修复方法:对总和取模26,确保索引始终在0-25范围内:

char rotate(char c, int key){
    int location;
    if(isupper(c)){
        location = c - 'A';
        // 先对key取模减少数值,再与location相加后再次取模,避免越界
        location = (location + key % 26) % 26;
        c = upper[location];
    }
    else if(islower(c)){
        location = c - 'a';
        location = (location + key % 26) % 26;
        c = lower[location];
    }
    return c;
}

或者更简洁的等价写法:

location = (location + key) % 26;

二、密钥的整数验证实现

当前代码用atoi转换密钥,但如果输入非数字字符串(比如"abc"),atoi会返回0,无法区分合法的0密钥和非法输入。需要遍历密钥字符串的每个字符,验证是否全为数字:

在main函数中添加验证逻辑:

int main(int argc, string argv[])
{
    if (argc != 2){
        printf("Usage: ./caesar key\n");
        return 1;
    }

    // 验证密钥是否全为数字
    string key_str = argv[1];
    for(int i = 0; i < strlen(key_str); i++){
        if(!isdigit(key_str[i])){
            printf("Usage: ./caesar key\n");
            return 1;
        }
    }

    int key = atoi(argv[1]);
    // 可选:若题目要求密钥为正整数,添加以下判断
    // if(key < 1){
    //     printf("Usage: ./caesar key\n");
    //     return 1;
    // }

    string word = get_string("plaintext: ");
    for(int i = 0; i < strlen(word); i++){
        word[i] = rotate(word[i], key);
    }
    printf("ciphertext: %s\n", word);
}

补充说明

  • isdigit函数依赖你已包含的<ctype.h>头文件,无需额外添加。
  • 验证通过后再调用atoi转换,确保得到合法的整数密钥。

内容的提问来源于stack exchange,提问作者tommy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 07:15:37