Thread: input validation - new to programming

  1. #1
    Registered User
    Join Date
    Oct 2003

    input validation - new to programming

    I am working on a program which requires a lot of simple input validation. Basically I ask several questions to which the user must input either 1, 2, or 3. Any input that is other than this will be rejected and the user must be prompted to enter either 1,2, or 3. I am new to C and programming in general so please keep that in mind! Here's the code:

    int maritalstatus
       printf("Enter \"1\" if Single, \"2\" if Married, or \"3\" if you are   Married but you want to withhold at the Single Rate: ");
    //check to see if input is not an integer. 
       if (scanf("%d", &maritalstatus) != 1)   
       goto maritalstat;
    //if input is an integer the switch statement starts.
       case 1 : break;
       case 2 : break;
       case 3 : break;
       default: goto maritalstat;
    There are a few problems I am having when I execute this. First of all when I enter a non integer as an input, such as an alphabetic character, an infinite loop seems to start. The screen keeps scrolling until I halt the program. Second of all even if I enter a 1, 2, or 3, the switch loop does not break. It goes back to the beginning and asks me to enter an input.
    I would appreciate if if you could tell me what I am doing wrong or perhaps suggest a better way of doing this. Thanks

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    There are some suggestions in the FAQ. And Prelude posted this a while back.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Oct 2003
    Thanks for the help Dave. That worked... just what I wanted!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Printing Length of Input and the Limited Input
    By dnguyen1022 in forum C Programming
    Replies: 33
    Last Post: 11-29-2008, 04:13 PM
  2. Problem getting the input from a temp variable into the Array
    By hello_moto in forum C++ Programming
    Replies: 3
    Last Post: 03-16-2006, 01:50 AM
  3. Input validation loop failure
    By MacNilly in forum C++ Programming
    Replies: 4
    Last Post: 03-01-2006, 03:29 AM
  4. Input Validation Question
    By zackboll in forum C Programming
    Replies: 14
    Last Post: 10-12-2004, 12:05 AM
  5. need help with some input
    By blindleaf in forum C Programming
    Replies: 2
    Last Post: 03-16-2003, 01:50 PM