c - 有无限循环,因为 scanf() 不会停止程序从用户那里获取条目
问题描述
我需要编写一个计算斐波那契数列的程序,但我因为这个无限循环而卡住了。
当我输入 -5 时,它会打印 Please enter "positive" term(s) number:。
然后我输入“a”并打印 Please enter "numeric" term(s) number:infinitely。
我不知道为什么会这样。谢谢你的帮助。
(注意:我尝试使用 fflush(stdin) 但没有解决这个问题。我想可能 \n 字符留在标准输入缓冲区中。)
#include <stdio.h>
void calculate_fibonacci_sequence(){
int n,is_entry_valid;
int flag = 0;
printf("Please enter term(s) number : ");
while(!flag){
is_entry_valid = scanf("%d",&n);
if(is_entry_valid == 1){
if(n > 0){
flag = 1;
}else{
printf("Please enter \"positive\" term(s) number: ");
}
}else{
printf("Please enter \"numeric\" term(s) number: ");
}
}
}
int main(){
calculate_fibonacci_sequence();
return(0);
}
解决方案
%d
告诉scanf
跳过任何前导空格,然后读取字符直到下一个非数字字符;该非数字字符留在输入流中。如果没有调用getchar
或fgetc
类似调用,该字符将不会被删除。
所以在else
你的陈述的分支中if (is_entry_valid == 1)
,你需要添加类似的东西
while ( getchar() != '\n' )
; // empty loop
这将从输入流中删除所有内容,包括换行符。
推荐阅读
- python - 如何让 pipenv 安装包子依赖项
- c# - 如何使用 websockets 在我的 Azure 应用服务 Web 应用和本地控制台应用之间建立连接?
- python - 根据 pivot_table 的输出动态重命名数据框
- amazon-web-services - 有条件地设置带有 IF 的标签在 cloudformation 模板中不起作用
- r - 使用separate() 分割不同大小的字符串
- javascript - 如何提高Javascript中代码的执行速度
- python - 无法使用python将数据库导入mysql
- typescript - 防止玩笑干扰打字稿
- kubernetes - EKS 负载均衡器上的 SSL(ACM)
- static - 如何将所有 Sapper 路由导出到静态文件中?