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

C语言字符数组输入输出异常求助:获取用户输入并正确打印

问题解决:C语言字符数组输入异常与字符串乱码问题

问题描述

尝试逐个获取用户输入的字符存入char数组,打印完整字符串并按顺序逐个输出数组元素,但运行时出现输入交互异常、字符串打印乱码的问题。

原代码

#include <stdio.h>

int main(void)
{
    char string[9];

    int i;
    int counter1 = 0;
    int counter2 = 0;

    for (i=0; i<=10; i++)
    {
        printf("Enter character for element %d: ", counter1);
        scanf("%c", &string[counter1]);
        counter1++;
    }
    printf("Your input: %s", string);
    printf("\nArray values:\n");

    while (counter2<=9)
    {
        printf("Element %d: %c\n", counter2, string[counter2]);
        counter2++;
    }
}

原运行输出

Enter character for element 0: w
w
Enter character for element 1: w
Enter character for element 2: w
Enter character for element 3: w
Enter character for element 4: w
Enter character for element 5: w
Enter character for element 6: w
Enter character for element 7: w
Enter character for element 8: w
Enter character for element 9: w
Enter character for element 10: w
Your input: wwwwwwwwwww�tI�(�)���Array values:
Element 0: w
Element 1: w
Element 2: w
Element 3: w
Element 4: w
Element 5: w
Element 6: w
Element 7: w
Element 8: w
Element 9: w

问题分析

  • 数组越界:定义的string数组长度为9,仅能存储索引0-8的元素,但循环执行了11次(i<=10),会往string[9]、string[10]写入数据,破坏数组外的内存空间,引发未定义行为。
  • 输入缓冲区残留换行符:使用scanf("%c")读取字符时,用户输入字符后按下的回车(\n)会留在输入缓冲区,下一次scanf会直接读取这个换行符,导致跳过输入提示,出现交互异常。
  • 字符串缺少终止符:C语言中printf("%s")要求字符串以\0(空字符)结尾,原代码未添加该终止符,导致打印时越界读取内存,出现乱码。

修正后的代码

#include <stdio.h>

int main(void)
{
    // 数组长度设为11(存储10个字符+1个终止符)
    char string[11];
    int i;

    for (i = 0; i < 10; i++)
    {
        printf("Enter character for element %d: ", i);
        // 使用空格过滤输入缓冲区的换行符
        scanf(" %c", &string[i]);
    }
    // 添加字符串终止符,确保printf("%s")正常工作
    string[10] = '\0';

    printf("\nYour input: %s\n", string);
    printf("Array values:\n");

    for (i = 0; i < 10; i++)
    {
        printf("Element %d: %c\n", i, string[i]);
    }

    return 0;
}

修正说明

  1. 调整数组长度:将数组长度设为11,预留一个位置存储字符串终止符\0,避免越界。
  2. 处理输入换行符:在scanf的格式字符串前添加空格(" %c"),空格会自动过滤输入缓冲区中的空白字符(包括换行符、空格等),解决交互异常问题。
  3. 添加终止符:在输入完成后手动添加string[10] = '\0';,确保printf("%s")能正确识别字符串结束位置,避免乱码。
  4. 简化循环逻辑:直接使用循环变量i作为索引,去掉多余的counter变量,代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:09:22