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

CS50 Substitution作业本地正常但check50检测失败求助

CS50 Substitution作业check50失败问题解决方案

核心问题分析

本地运行正常但check50检测失败,且提示"预期输出包含'ciphertext: ...'但实际为空",大概率是输出格式不匹配、程序提前退出或标准输出处理错误导致的,和函数返回类型(string/void)无关。

具体排查与修复步骤

1. 严格匹配输出格式

题目要求必须输出固定格式:

  • 前缀必须是ciphertext: (冒号后有一个空格)
  • 密文后必须加换行符

错误示例:

// 只打印密文本体,缺少前缀
printf("%s", ciphertext);
// 前缀写错(无空格)
printf("ciphertext:%s\n", ciphertext);

正确示例:

  • 若用返回string的encrypt函数:
int main() {
    // ... 密钥验证、获取明文逻辑 ...
    string ciphertext = encrypt(plaintext, key);
    printf("ciphertext: %s\n", ciphertext); // 完整格式+换行
    free(ciphertext); // 动态分配的内存记得释放
}
  • 若用void类型直接打印的encrypt函数:
void encrypt(string plaintext, string key) {
    printf("ciphertext: "); // 先打印前缀
    for (int i = 0; plaintext[i] != '\0'; i++) {
        // ... 加密逻辑 ...
        printf("%c", encrypted_char);
    }
    printf("\n"); // 最后加换行
}

2. 修复密钥验证逻辑

如果程序对合法密钥的验证出错,会直接退出且不输出密文,导致check50捕获不到结果。需确保:

  • 验证密钥长度是否为26
  • 验证密钥是否全为字母(大小写不敏感)
  • 验证密钥是否无重复字符
  • 错误信息必须输出到stderr,而非stdout,避免干扰check50检测:
if (argc != 2 || !is_valid_key(argv[1])) {
    fprintf(stderr, "Usage: ./substitution key\n"); // 用fprintf输出到stderr
    return 1;
}

3. 处理标准输出缓冲问题

C语言中printf默认会缓冲输出,若程序结束前未刷新缓冲区,check50可能捕获不到内容。可通过两种方式解决:

  • 输出时加换行符(\n),自动触发缓冲刷新
  • 手动调用fflush(stdout)确保输出立即写入:
printf("ciphertext: %s", ciphertext);
fflush(stdout);
printf("\n");

4. 模拟check50输入测试

本地模拟check50的自动输入方式,验证输出是否符合要求:

# 用管道传入明文,模拟check50的自动化测试
echo "HELLO WORLD" | ./substitution ABCDEFGHIJKLMNOPQRSTUVWXYZ

若输出不是ciphertext: IFMMP XPSME,则说明格式或加密逻辑有问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:40:19