c - 无法构建“输入 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)'的整数参数”警告,我似乎不明白我被警告的是什么。
解决方案
fflush(stdin); //I heard this has to be used because scanf keeps the enter key in
那是错误的,fflush
ingstdin
是未定义的行为,您需要做的是消耗上一次扫描留下的换行符,只需从
scanf_s("%c", &l);
至
scanf_s(" %c", &l); // Notice the space before %
推荐阅读
- android - 一个 RenderFlex 在底部溢出了 14 个像素。相关的导致错误的小部件是 AlertDialog
- django - QuerySet' 对象没有属性 'posts'
- .net - 在.net SortedDictionary *无* LINQ 中将“A-1”排在“A-10”之前
- java - 是否有 JPA / JPQL 查询来搜索春季作为 JSON 传递的实体子集?
- statistics - 哪些特征值与负度量相关
- python - 如何根据python数据框中的if行条件找到最接近的col名称?
- php - Wordpress 中的空 GET 参数(使用 Nginx)
- c++ - 如何访问私有 typedef 作为公共函数中的参数
- python - 需要使用 < 和 > 运算符比较 Pandas 中的 DataFrames 以获取列中的特定数据
- arrays - 如何到达指针数组指向的数组?