Search code examples
cwhile-loopscanfinfinite-loopstdio

Having infinite loop because scanf() does not stop the program to take entry from user


I need to write a program which calculates fibonacci sequence but I stuck because of this infinite loop.

When I enter -5 it prints Please enter "positive" term(s) number:.

Then I enter "a" and it prints Please enter "numeric" term(s) number: infinitely.

I couldn't figure out why it is. Thanks for any help.

(note : I tried to use fflush(stdin) but didn't fix this. I thought maybe \n char left in the stdin buffer.)

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

Solution

  • %d tells scanf to skip over any leading whitespace, then read characters up to the next non-digit character; that non-digit character is left in the input stream. Without a call to getchar or fgetc or similar, that character will not be removed.

    So in the else branch of your if (is_entry_valid == 1) statement, you'll need to add something like

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

    which will remove everything up to and including the newline from the input stream.