Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 218
  • Last Modified:

Beginner to C - Please help with scanf()

Hi,
      I am trying to read in an numeric variable with scanf(), then, based upon logic, goto the correct section of my program. I find that if I input an Alpha character instead of a number, it loops into hell.  Any ideas how I can implement error checking or force numeric input. My initial section of read in code is below:

Thanks
Paul

int operation,choice;
option:printf("\nMAIN MENU\n\n\n");
  printf("1: Dollars to some other currency\n\n");
  printf("\n2: Euros to dollars\n\n");
  printf("\n3: Display currency equivalents for USD\n\n\n");
  printf("\n4: Quit this program\n\n");/*Advise user of options*/
  operation=0; /*set menu choice default to zero*/
  scanf("%d",&operation);/*read in user option for operation to perform*/
  if(operation == 1)goto conv1; /*CHOICE 1 ADVANCE TO CONV1 LABEL*/
  if(operation == 2)goto conv2; /*CHOICE 2 ADVANCE TO CONV2 LABEL*/
  if(operation == 3)goto display; /*CHOICE 2 ADVANCE TO DISPLAY LABEL*/
  if(operation == 4)goto leave; /*CHOICE 3 ADVANCE TO LEAVE LABEL*/
  else goto oops;    /*ANY OTHER CHOICE ADVANCE TO OOPS LABEL*/
oops:printf("\n\nPLEASE CHOOSE A VALID OPTION");goto option;  /*LOOP BACK TO MAIN OPTIONS MENU ON INVALID CHOICE*/
0
simpsop
Asked:
simpsop
1 Solution
 
gj62Commented:
It is generally considered better to do this:

char inputStr[20]; - big enough to hold a reasonable number of chars...

scanf("%s", inputStr);
operation = atoi(inputStr);
if (operation < 1 || operation > 4)
   printf("please enter a number between 1 and 4\n");

etc...
0
 
simpsopAuthor Commented:
Perfect! Worked like a charm.

Thank you for the fast response!

Paul
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now