无法建立“输入y以循环”程序

问题描述

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

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');
}

我还收到“ scanf(_s)'缺少整数参数,该参数与转换说明符'2'相对应”警告,而且我似乎不明白所警告的内容。

解决方法

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

这是错误的,fflushstdin是不确定的行为,您需要做的是消耗上一次扫描留下的换行符,只需从

切换即可
    scanf_s("%c",&l);

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...