首页 > 解决方案 > 有无限循环,因为 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);
}

标签: cwhile-loopscanfinfinite-loopstdio

解决方案


%d告诉scanf跳过任何前导空格,然后读取字符直到下一个非数字字符;该非数字字符留在输入流中。如果没有调用getcharfgetc类似调用,该字符将不会被删除。

所以在else你的陈述的分支中if (is_entry_valid == 1),你需要添加类似的东西

while ( getchar() != '\n' )
  ; // empty loop

这将从输入流中删除所有内容,包括换行符。


推荐阅读