• C

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*/
simpsopAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
simpsopAuthor Commented:
Perfect! Worked like a charm.

Thank you for the fast response!

Paul
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.