Below is a wee program written in C which prompts the user for two
integers between 1 and 100 and multiplies the two numbers. It all works
fine and dandy as it is, unless you enter anything but a valid integer,
then you get stuck in an infinite loop.

The answer to this is beyond the scope of the module I am currently
studying but I'm too impatient to wait until I get to some of the more
advanced modules to learn it. I was told it's a limitation with scanf.

So does anyone have a nice solution on how I can catch any input that is
not an integer and then return to the appropriate prompt?

Cheers
Kerry

*************************************************************************

/*    This program prompts the user for two numbers under 100.
*     it then tests to make sure both numbers are below 100,
*     then multiplies the numbers and displays the answer
*/

#include <stdio.h>
#include <conio.h>
#define MAXSIZE 100     // Maximum number size
#define MINSIZE 1       // Minimum number size

int answer(int val1, int val2);

void main()
{
   int num1 = 0, num2 = 0;
   printf("Enter a number between %d and %d: ", MINSIZE, MAXSIZE);
   scanf("%d", &num1);

   while ((num1 < MINSIZE) || (num1 > MAXSIZE))
      {
      printf("%d is outside the boundry given\n\n", num1);
      printf("Enter a number between %d and %d: ", MINSIZE, MAXSIZE);
      scanf("%d", &num1);
      }

   printf("Enter another number between %d and %d: ", MINSIZE,
 MAXSIZE);
   scanf("%d", &num2);

   while ((num2 < MINSIZE) || (num2 > MAXSIZE))
      {
      printf("%d number is outside the boundry given\n\n", num2);
      printf("Enter another number between %d and %d: ", MINSIZE,
 MAXSIZE);
      scanf("%d", &num2);
      }

   printf("%d times %d equals %d", num1, num2, answer(num1, num2));

   getch();
}

int answer(int val1, int val2)
{
   return val1 * val2;
}


Reply via email to