-
Data Validation problem
Hi, I was wondering if I could get some advise.
This is just a small part of the code.
When the user inputs the wrong data, he is prompted to enter the correct data, but the only problem is that the program ends and the user has to start all over.
Is there a way I could get the user back to the beginning, where the user is prompted to enter two hex numbers without the program ending.
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
int reply;
puts("\n****************************************** ******************");
puts("\nEnter a menu number selection between 1 and 4, 0 to exit: ");
puts("\n****************************************** ******************");
scanf("%d", &reply);
switch (reply)
{
case 0:
exit(0);
case 1:
{
int a, b, c, r;
printf ("Two numbers please.\n");
r = scanf ("%x%x", &a, &b);
if ( r == 2 )
{
c = a + b;
printf ("%#x", c);
}
else
printf("hex please");
break;
}
default:
puts("Between 1 and 4, please!\n");
} /* end of switch */
return 0;
}
-
You need a loop and a flag to check if input is correct, somethin like.
Code:
flag = 0;
while(!flag)
{
/* code goes here */
if(r == 2)
{
c = a + b;
printf ("%#x", c);
flag = 1;
}
else
printf("hex please");
}
The loop only stops when flag is non-zero and flag is only changed if input is correct.
Hope this gives you some help.
You could even replace the flag with a break.
Code:
while(1)
{
/* code goes here */
if(r == 2)
{
c = a + b;
printf ("%#x", c);
break;
}
else
printf("hex please");
}
-
/* a simple menu */
Code:
do
{
printf("\nPlease enter your choice for routine - 1 to 4\n");
printf("Enter zero to exit");
scanf("%d", choice);
switch(choice)
{
case 0: printf("\n\nGoodbye");
break;
case 1: /*whatever*/
break;
case 2: /*whatever*/
break;
case 3: /*whatever*/
break;
case 4: /*whatever*/
break;
default: printf("\n\nInvalid entry try again");
}
} while(choice);
-
It almost works. It's getting closer I think. What's happening now is when I enter a non hex number, I get an endless loop. I'm not sure why it's happening.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
int reply;
puts("\n****************************************** ******************");
puts("\nEnter a menu number selection between 1 and 4, 0 to exit: ");
puts("\n****************************************** ******************");
scanf("%d", &reply);
switch (reply)
{
case 0:
exit(0);
case 1:
{
int a, b, c, r;
int flag ;
while (1)
{
printf ("Two numbers please.\n");
r = scanf ("%x%x", &a, &b);
if ( r == 2 )
{
c = a + b;
printf ("%#x", c);
flag = 0;
}
else
printf("hex please");
}
break;
}
default:
puts("Between 1 and 4, please!\n");
} /* end of switch */
return 0;
}