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

使用scanf %c读取字符串为何出现乱码字符?

输入输出异常问题分析与解决

问题场景

输入字符串love时,程序输出l Φ■,与期望的输入输出一致不符,代码如下:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main()
{
    char s[40];
    scanf("%c", &s);
    printf(s);

    return 0;
}

问题原因

  1. 字符读取不完整:scanf("%c", &s); 使用的%c格式符仅能读取单个字符,输入love时只有第一个字符l被写入数组s的起始位置,剩余字符留在输入缓冲区未被处理。
  2. 缺少字符串结束符:C语言中字符串必须以\0作为结束标记,scanf("%c")不会自动添加该标记。而printf(s)打印字符串时会持续读取内存直到找到\0,数组s未初始化的部分是随机垃圾值,因此会输出乱码。

修正方案

将scanf的格式符改为%s,它会自动读取连续的非空白字符组成字符串,并在末尾添加\0,同时数组名s本身就是首地址,无需添加&:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main()
{
    char s[40];
    scanf("%s", s);
    printf(s);

    return 0;
}

额外注意事项

  • 若需要读取包含空格的完整输入行,可使用fgets(s, sizeof(s), stdin),但注意该函数会把输入末尾的换行符也读入字符串,需手动去除(比如直接将换行符位置替换为\0)。
  • 局部数组建议初始化,比如char s[40] = {0};,避免未初始化的垃圾值干扰程序行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:05:20