Thread: Validate input value

  1. #1
    Registered User
    Join Date
    Mar 2009

    Validate input value

    I have a program with a menu like this:

     char c;
     char option;
         printf("\n1.Insert number: \n");
         printf("2. Option 2\n");
         printf("3. Option 3\n");
         printf("4. Option 4\n");
         printf("5. Quit\n");     
         printf("Enter Option: ");
         scanf("%c", &option);  
           printf("Insert number:");	           
            while((c=getchar()) != '\n'){       
    	//call function here
        else if(option=='2'){
    	//do something
        else if(option=='3'){
    	//do something
        else if (option=='4'){
           //do something
       else if(option=='5'){	 
    	printf("The program exits now!\n");
       else  {
           printf ("Invalid menu choice - try again\n")			
    } while (option != '5');
    I want to validate that the entered option is acceptable. The system will check that the user entered an integer numeric value between 1-5. If the input is incorrect then the system will respond “Invalid menu choice ” and present the user with the menu.

    When I enter 1, or 2,3,4,5.... my program works fine. But when I enter 125, the program jumps to option 1.

    I know that I am wrong at getchar() line since it only gets a character. but I don't know how to fix it.

    Any helps would be appreciated.
    Last edited by aladin; 03-21-2009 at 08:02 AM.

  2. #2
    Registered User
    Join Date
    Sep 2001
    Yeah, no matter how many characters you enter, you're only going to get the first digit or character.

    You could use scanf instead of getchar to specify that you're just looking for a single, decimal integer value, and then use int's instead of the char equivalents in your case statements.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. For loop problems, input please.
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-22-2007, 03:54 AM
  2. I would love some input on my BST tree.
    By StevenGarcia in forum C++ Programming
    Replies: 4
    Last Post: 01-15-2007, 01:22 AM
  3. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  4. Structure and Linked List User Input Question
    By kevndale79 in forum C Programming
    Replies: 16
    Last Post: 10-05-2006, 11:09 AM
  5. need help with some input
    By blindleaf in forum C Programming
    Replies: 2
    Last Post: 03-16-2003, 01:50 PM