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

为什么for循环中给数组元素赋值变量c,数组却未被正确填充?

问题排查与修正方案

核心错误1:数组赋值逻辑错误

你声明的cipher是局部变长数组,未手动初始化时元素默认是随机垃圾值。代码中使用cipher[i] += c是在原有垃圾值的基础上累加c,并非直接赋值,自然无法得到正确的密文存储结果,把所有+=改为=即可。

核心错误2:输出逻辑错误

  • %c是单个字符的格式控制符,cipher是数组名(本质是指向数组首元素的指针),直接将指针强转为char打印,输出的内容和你存储的密文完全无关
  • 你要输出完整密文有两种方案:要么循环遍历cipher数组逐个打印每个元素转成char类型,要么将cipher改为char类型数组,末尾补字符串结束符'\0'后直接用%s打印。

可选优化点

开头的参数判断if(argc < 2 || argc<2 )是重复冗余的,直接写if (argc != 2)即可,因为凯撒密码只能接收1个密钥参数,参数数量多于2也不符合使用规则。


修正后可运行代码

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

int main (int argc, string argv[])
{
    // 修正参数判断逻辑
    if(argc != 2)
    {
        printf("Usage: ./caesar key \n");
        return 1;
    }

    for (int i = 0; i < strlen(argv[1]); i++)
    {
        if(!isdigit(argv[1][i]))
        {
            printf("Usage: ./caesar key \n");
            return 1;
        }
    }

    int key = atoi(argv[1]);
    string initial_text = get_string("plaintext: ");
    int n = strlen(initial_text);
    // 改为char数组,多留一位存结束符
    char cipher[n + 1];
    int i = 0;

    for (i = 0; i < n; i++)
    {
        int c = 0;
        if (isupper(initial_text[i]))
        {
            c = (((int)initial_text[i] - 65 + key) % 26) + 65;
            // 改为直接赋值
            cipher[i] = c;
        }
        else if (islower(initial_text[i]))
        {
            c = (((int)initial_text[i] - 97 + key) % 26) + 97;
            cipher[i] = c;
        }
        else
        {
            c=initial_text[i];
            cipher[i] = c;
        }
    }
    // 补字符串结束符
    cipher[n] = '\0';
    // 用%s打印完整字符串
    printf("ciphertext: %s\n", cipher);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:48:05