Results 1 to 2 of 2

Thread: error trapping with char's

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jan 2001
    Location
    UK
    Posts
    205

    error trapping with char's

    i am reading in values from a menu. however, if the user enters a char instead of an int, which is the type of the variable for reading values; the program goes into a never ending loop. How do i scanf the value into a char, check it is numerical, ie a number. and then convert it into an int. Some of this i know, like the conversion. I use atoi to convert the char to an int.

    Here is my example code:
    Code:
    do{
      bInValid = true;
      printf("\n\nPlease enter an option: ");
      scanf("%d",&iChoice);
    
      if(iChoice < 1 || iChoice > iNumOpts)
      {
        bInValid = false;
        printf("\n\n*** Input error, try again! ***");
      }
    }while(!bInValid);
    if(iChoice == 1)
    {
      if(iVal == 1)
        iChoice = 0;
      else
        iChoice = iVal / 10;
    }
    else
      iChoice = iVal * 10 + iChoice;
    		
      clrscr();
    
      return iChoice;

  2. #2
    Fanatic Member Wynd's Avatar
    Join Date
    Dec 2000
    Location
    In a bar frequented by colossal death robots
    Posts
    772
    Try using gets(). That way you can take in a string and check if it's a number and act accordingly.
    Alcohol & calculus don't mix.
    Never drink & derive.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width