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

C语言if语句内printf重复输出问题求助

解决C语言中printf重复输出的问题

问题原因

问题出在输入缓冲区的残留字符:当你用scanf("%d", &func);读取数字后,按下的回车键(\n)会留在输入缓冲区中。后续执行scanf("%c", &confirm);时,它不会等待用户输入,直接读取了缓冲区里的\n——这个字符既不是Y/y也不是N/n,程序会跳出当前分支回到外层循环,再次执行printf("Do you want to exit? [Y/N] ");,最终导致重复输出。

解决方案

有两种简单的修复方式:

方法一:用getchar()清除缓冲区残留的换行符

在读取确认字符前,手动吃掉缓冲区里的换行符:

char confirm;
printf("Do you want to exit? [Y/N] ");
getchar(); // 清除之前输入留下的换行符
scanf("%c", &confirm);

方法二:在scanf格式串前添加空格跳过空白字符

修改读取确认字符的scanf语句,利用格式串前的空格自动跳过所有空白字符(包括换行、空格、制表符):

scanf(" %c", &confirm); // %c前的空格会跳过空白字符

修改后的完整代码(以方法二为例)

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

int main(void)
{
    int repeat = 1;
    while(repeat == 1)
    {
        
        printf("0: Exit\n\n");

        int func = -1;
        printf("Choose an option: ");
    
        while (1)
        {
            scanf("%d", &func);

            if (func == 0)
            {
                char confirm;
                printf("Do you want to exit? [Y/N] ");
                scanf(" %c", &confirm); // 添加空格跳过空白字符
                if (confirm == 'y' || confirm == 'Y')
                {
                    repeat = -1;
                    break;
                }
                else if (confirm == 'n' || confirm == 'N')
                {
                    break;
                }
            }

            if (repeat == -1)
                break;
        }
    }       
    printf("Program finished\n");
    return 1;
}   

void clearScreen()
{
    system("clear || cls");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:37:11