问题描述
我需要编写一个程序来计算斐波那契数列,但我因为这个无限循环而卡住了。
当我输入 -5 时,它会打印 Please enter "positive" term(s) number:.
然后我输入“a”并打印请输入“数字”术语编号:无限。
我不明白为什么会这样。感谢您的帮助。
(注意:我尝试使用 fflush(stdin) 但没有解决这个问题。我想可能 \n char 留在标准输入缓冲区中。)
#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
这将从输入流中删除包括换行符在内的所有内容。
,fgets
可用于读取一行,然后使用 sscanf
解析该行。
在非整数输入的情况下,问题输入已被 fgets
删除,因此重试可接受的输入很容易。
#include <stdio.h>
void calculate_fibonacci_sequence(){
char line[100] = "";
int n,is_entry_valid;
int flag = 0;
printf("Please enter term(s) number : ");
while(!flag){
fgets ( line,sizeof line,stdin);
is_entry_valid = sscanf(line,"%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);
}
,
当您收到错误的用户输入时,您需要刷新 stdin
以清理输入缓冲区,此代码应该可以工作:
#include <stdio.h>
void calculate_fibonacci_sequence(void)
{
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 c;
// Flush stdin
while ((c = fgetc(stdin)) != EOF && c != '\n');
}
}
}
int main(void)
{
calculate_fibonacci_sequence();
return(0);
}