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

C语言scanf输入异常:输入单词后无法输入目标字符的问题

解决C程序中第二个scanf被跳过的问题

问题原因

使用scanf("%s", word)读取单词时,该函数仅会读取空格或换行符之前的字符。输入单词后按下回车,换行符\n会残留在输入缓冲区中。后续的scanf("%c", &letter)会直接读取这个残留的换行符,而非等待用户输入目标字符,因此程序直接跳过输入步骤,统计结果为0。

解决方法

有两种简洁有效的修复方式:

方式1:在第二个scanf格式串前添加空格

在%c格式说明符前加一个空格,格式串会自动跳过所有空白字符(包括换行、空格、制表符),直到读取到非空白字符为止。这是标准且推荐的写法:

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

方式2:用getchar()清除缓冲区残留换行符

在第一个scanf之后调用getchar(),手动吃掉缓冲区中残留的换行符:

scanf("%s", word);
getchar(); // 清除输入后的换行符

修正后的完整代码

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

int main(){
    int cont = 0;
    char word[50], letter;
    int i;
    printf("enter the word: ");
    scanf("%s", word);
    printf("enter the letter you want to know how many times it repeats itself: ");
    scanf(" %c", &letter); // 修复点:添加空格跳过空白字符
    for (i=0; i < strlen(word); i++){
        if (letter == word[i])
        {
            cont += 1;
        }
    }
    printf("the letter you typed is repeated %d times\n", cont); // 新增换行符优化输出格式
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:48:30