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

C语言替换元音为数字后长单词输出末尾出现随机额外字符求助

问题:C语言字符串替换后末尾出现随机乱码

我写了一段C语言代码,把元音字母(u除外)替换成对应的数字,短单词运行正常,但输入长度超过9或10个字母的单词时,输出末尾会多出两个随机字符,有时候是菱形问号乱码。我听说要给字符串加空字符,但不知道具体怎么操作,也不确定能不能解决问题。

原代码

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

int main(void)
{
    string word = get_string("Give me a word: " );
    int j = strlen(word);
    int i;
    char new[j + 1];

    new[0] = '\0';

    for(i = 0; i < j; i++)
    {
        if (word[i] == 'e')
        {
            new[i] = '3';
        }
        else if (word[i] == 'i')
        {
            new[i] = '1';
        }
        else if (word[i] == 'a')
        {
            new[i] = '6';
        }
        else if (word[i] == 'o')
        {
            new[i] = '0';
        }
        else
        {
            new[i] = word[i], 0;
        }
    }
    printf("%s\n", new);
}

错误输出示例(输入coordination时的3次结果)

c00rd1n6t10n�U
c00rd1n6t10nEV
c00rd1n6t10nQV

解决方案

问题根源就是缺少字符串结束符\0。C语言里的字符串必须以空字符\0结尾,否则printf("%s")这类函数会持续读取内存,直到偶然碰到一个\0,这就是末尾随机乱码的原因。

你的代码里虽然写了new[0] = '\0';,但循环过程中会覆盖这个位置,而且循环结束后没有在new的有效字符末尾补上\0。

修复步骤:

  1. 删除无用的new[0] = '\0';语句,循环会覆盖这个位置,起不到作用。
  2. 循环结束后,在new的第j位(对应原单词长度的位置)添加\0,因为原单词的有效字符下标是0到j-1,j的位置正好是字符串末尾。
  3. 去掉else分支里多余的, 0,逗号表达式在这里没有意义,直接赋值即可。

修复后的代码

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

int main(void)
{
    string word = get_string("Give me a word: " );
    int j = strlen(word);
    int i;
    char new[j + 1];

    for(i = 0; i < j; i++)
    {
        if (word[i] == 'e')
        {
            new[i] = '3';
        }
        else if (word[i] == 'i')
        {
            new[i] = '1';
        }
        else if (word[i] == 'a')
        {
            new[i] = '6';
        }
        else if (word[i] == 'o')
        {
            new[i] = '0';
        }
        else
        {
            new[i] = word[i];
        }
    }
    new[j] = '\0'; // 关键:添加字符串结束符
    printf("%s\n", new);
}

这样修改后,printf会在new[j]的位置停止读取,不会越界访问内存,末尾的随机乱码就会消失。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:55:54