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

C语言逐字符输入字符串时索引0输入被跳过的问题排查

问题:逐字符输入时跳过索引0的输入

我尝试用for循环实现C语言的逐字符输入生成字符串,但每次运行都会跳过索引0的输入,无法理解其中原因。

我的代码

// take char by char input and print it as string

#include <stdio.h>

void input(){
    printf("this program takes char by char input for string\n");
    int length;
    printf("provide us with the total length of the string : ");
    scanf("%d", &length);
    char arr[length];
    char placeholder;
    for(int i=0;i<length;i++){
        if(i==length){
             arr[i]='\0';
        }
        printf("input char[%d] : ",i);
        scanf("%c", &placeholder);
        printf("\n");
        arr[i]=placeholder;
        }
}

int main(){
    input();
}

运行输出

this program takes char by char input for string
provide us with the total length of the string : 10
input char[0] : // 此处被跳过
input char[1] : // 这里才能输入值


问题原因

核心问题是输入缓冲区残留的换行符:当你用scanf("%d", &length)输入数字并按下回车后,输入缓冲区里会留下数字10和一个换行符\n。scanf("%d")只读取了数字部分,换行符被留在了缓冲区中。后续第一次执行scanf("%c", &placeholder)时,它会直接读取这个残留的换行符,导致第一个字符的输入被跳过。

另外你的代码还有一个逻辑错误:循环条件是i<length,所以i永远不会等于length,循环里的if(i==length)分支永远不会执行,也就无法给字符串添加结束符'\0'。

解决方案

1. 清空输入缓冲区的残留换行符

在读取完length后,调用getchar()读取并丢弃缓冲区里的换行符:

scanf("%d", &length);
getchar(); // 清除缓冲区中的换行符

2. 让scanf自动跳过空白字符

在%c格式串前添加一个空格,scanf会自动跳过所有空白字符(包括换行、空格、制表符):

scanf(" %c", &placeholder); // 注意%c前的空格

3. 修复字符串结束符的问题

声明数组时多预留一个字节的空间,循环结束后手动添加结束符:

char arr[length + 1]; // 多留一个位置存'\0'
// ...循环输入完成后...
arr[length] = '\0';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 13:23:19