Ray Ban
Ray Ban

Reputation: 67

Validate input and ask again if invalid

In this code I have several querys for user input. If there is an invalid input like 'r' instead of 4, I want my programm to say "invalid input" and ask for another user input. I tried a lot but I couldn't get it to work. I commented the problematic locations in the code. Thanks for help.

#include <stdio.h>

int main()
{ 
double Operand1;
double Operand2;
int Menuchoice; 
int Input;
char Dummy;
double Result;

do
{

  printf("Simple Calculator\n");
  printf("========================\n");
  printf("\n");
  printf("1. Addition\n");
  printf("2. Subraction\n");
  printf("3. Multiplication\n");
  printf("4. Division\n");
  printf("9. Quit\n");


  Input = scanf("%i", &Menuchoice);  // At this point I want to check if there is a valid input and 
  do scanf("%c", &Dummy);            //  if not the programm should ask again
  while (Dummy != '\n');

  if(Input)
  {
     switch(Menuchoice)
     {
        case 1: printf("Type in the first operand:\n");
                scanf("%lf", &Operand1)                     // Here I want to validate the input         
                printf("Type in the second operand:\n");    // again and the programm should also ask 
                scanf("%lf", &Operand2)                     // again if it was invalid
                printf("%lf + %lf = %lf\n", Operand1, Operand2, Result);
                break;
        case 2: 
        case 3: 
        case 4: 
        default: printf("No valid input!\n");
                break;
     }
  }

}while (Menuchoice != 9);

 return 0;
}

Upvotes: 1

Views: 568

Answers (1)

Amessihel
Amessihel

Reputation: 6384

Manual page of scanf:

On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.

So here is a sample which could lead you to solve your problem:

#include <stdio.h>

int main (int argc, char* argv)
{
  double o;
  int res;

  // To illustrate, I chose to set up an infinite loop.
  // If the input is correct, we'll "break" it
  while(1)
    {
      printf("Enter a double: ");
      res = scanf("%lf",&o);

      // Success = 1 read input
      if (res == 1)
      {
        printf("Yahoo, got it right: %f\n",o);
        break; // We exit the loop
      }

      // Ah, we failed
      printf("Please retry.\n");
      // popping the CR character to avoid it to be got by the next scanf()
      getchar();

      // Here we go for another loop.
    }

    // Good, we got our double.
    printf("Hey, sounds like we got outside this infinite loop.\n");
}

Example:

user@so:~$ ./a.out 
Enter a double: r
Please retry.
Enter a double: f
Please retry.
Enter a double: 6.543
Yahoo, got it right: 6.543000

Keep in mind this check is not perfect. For example, "frg6sgg" will success and be displayed as 6.0000000 by printf().

Upvotes: 2

Related Questions