C scanf not working in recursive function -


this question has answer here:

i trying write function takes , checks if input integer between 1 , 1000. if not, calls itself. however, if give wrong input, example, "f" , doesn't stop scanf, rather becomes infinite loop. suggestion? input buffer?

#include <stdio.h>  int num,input;   int take_input() {    num =  scanf("%d", &input);    if( num != 1 || input < 1 || input > 1000 )   {     printf("input must between 1 , 1000");     take_input();   }   return 1; }  int main() {     take_input(); } 

first: don't need check if (num != 1) in second test... there if first test false.

second: passing 1 argument read: scanf return either 1 or 0 (if didnt read correctly). happens is: if read 1 number num have value 1 , exit right after in first if.

to make recursion work have to:

 if(num != 1 )     return 1;  if( input < 1 || num > 1000 )   {     printf("input must between 1 , 1000");     take_input();  } 

this way keep asking new value while current value not in specified interval.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -