Infinite loops caused by string value

I am creating a simple program (sum of two numbers) in which program ask user to input integer value if he adds wrong value the program gives error and starts program again but when user add string value it starts to loop again and again first statement of program I have all correct conditions for integer values but none for string I want to know the problem why its printing the first statement again and again for string value! I have used goto statement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
 
int main()
{
   int a, b, c;
   
s1:printf("Enter the first number between 1-10\n");
   scanf("%d", &a);
   
   if(a<1 || a>10)
   {
   	printf("Out of limit! Please enter value again.\n");
   	goto s1;
   }
   
   else
   {
   s2:printf("Enter the second number 11-20\n");
      scanf("%d", &b);
      
      if(b<11 || b>20)
      {
      	printf("Out of limit! Please enter value again.\n");
   	    goto s2;
	  }
	  
	  else
	  {
      c=a+b;
      printf("Sum = %d", c);
      }
   }
}
Last edited on
You need to check if the value was read correctly by looking at the return value of scanf. If the return value is not the same as the number of values being read (in this case 1) then something went wrong. If this happens you will have have to discard the erroneous input line, because otherwise it will still be there and cause an error next time you try to read. I don't know how you do that with scanf but perhaps someone else can tell you otherwise you can probably find a way if you make some research.
I have found a problem but don't know how to fix it! its actually problem of scanf buffer. How can I flush the buffer of scanf?
Found it using while(getchar() != '\n'); after scanf :P
Topic archived. No new replies allowed.