2
votes

I'm trying to create a C program to allow the user to input an integer number greater than 0, but if any other type is entered make the user try again until they enter an integer.

int minBet;

printf("Enter integer"\n);

while(scanf("%d",&minBet)!=1)
{
    printf("Must be an integer value greater than 0\n");
    scanf(" %d",&minBet);
}

When a non integer value is entered the printf statements loops infinitely. How can I solve this?

can only use stdio.h and NO global varables

2
hint use break keyword and only one scanf; - Ahmed Masud
also you should post code such that someone else can simply compile it. - Ahmed Masud

2 Answers

1
votes

If the input character doesn’t match the coversion, it’s left in the input stream to foul up the next read - you’ll have to get rid of it using getchar or fgetc.

while ( scanf( “%d”, &minBet ) < 1 )
{
  getchar();
  printf( “You entered a non-numeric value, try again: );
}
0
votes

When you type let's say e, you type e and then press the ENTER key. So there are now 2 characters in the input buffer. scanf("%d") reads the e , but the newline character is still in the input buffer.

A simpler solution to your immediate problem is to add a getchar() after each scanf("%d"). This code will work .

#include <stdio.h>
#include <string.h>

int main(void)
{
    int minBet;

printf("Enter integer \n");

while(scanf("%d",&minBet)!=1)
{
    getchar(); 
    printf("Must be an integer value greater than 0\n");
}
}

Additionally your code printf("Enter integer"\n); is wrong.It should be

printf("Enter integer \n");