首页 > 解决方案 > 无法构建“输入 y 循环”程序

问题描述

我现在仍在学习 C 的基础知识,我想构建一个简单的“输入 y 循环程序”,我在很多控制台程序中都看到过,并编写了以下代码来测试它。但是,当我执行它时,它会按预期工作一次,之后程序就会退出。如果有人告诉我我在这里做错了什么,那将对我有很大帮助:

int main()
{
char l;
    do
    {
        printf("Loop successful.\n");
        fflush(stdin);  //I heard this has to be used because scanf keeps the enter key in buffer or something like that
        scanf_s("%c", &l);
    } while (l == 'y');
}

我还收到一个“缺少与转换说明符'2'相对应的'scanf(_s)'的整数参数”警告,我似乎不明白我被警告的是什么。

标签: cloopsdo-while

解决方案


fflush(stdin);  //I heard this has to be used because scanf keeps the enter key in 

那是错误的,fflushingstdin是未定义的行为,您需要做的是消耗上一次扫描留下的换行符,只需从

    scanf_s("%c", &l);

    scanf_s(" %c", &l); // Notice the space before %

推荐阅读