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

scanf仅生效一次?C语言连续字符输入异常问题求助

问题:无法输入第二个字符,程序输出异常

我无法理解这段代码为何运行异常——单独运行每一部分时都能正常工作,但组合到一起就不行。

代码示例

#include <stdio.h>

int main()
{
    ///////part 1//////////
    char ch;
    printf("Enter a number between a-z or A-Z: ");
    scanf("%c",&ch);
    printf("The Char's value in the ASCII table is %d\n",ch);
    printf("The following char is %c \n",ch+1);
     /////////// part 2
    char up;
    printf("enter a char between a-z: ");
    scanf("%c",&up);
    printf("upper: %c ",up-32);

    return 0;
}

运行结果

Enter a number between a-z or A-Z: a
The Char's value in the ASCII table is 97
The following char is b 
enter a char between a-z: upper: � 

请问为何无法输入第二个字符(up),且输出位于同一行?


问题原因

第一个scanf("%c", &ch)读取你输入的字符后,输入缓冲区里还残留着你按下的换行符(\n)。第二个scanf("%c", &up)会直接读取这个换行符,而不是等待你输入新的字符。这就导致程序跳过了输入步骤,直接执行后续的printf:换行符的ASCII值是10,10-32等于-22,对应不可打印的乱码字符�,所以出现了异常输出。

解决方法

有两种简单的修复方式:

  • 方式一:在第二个scanf前调用getchar(),手动清除缓冲区里的换行符:
    // 在第二个scanf前添加
    getchar();
    scanf("%c",&up);
    
  • 方式二:修改scanf的格式控制字符串,在%c前加一个空格,让它自动忽略所有空白字符(包括换行、空格、制表符):
    scanf(" %c",&up); // 注意%c前面的空格
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:40:12