Thread: what is wrong with this simple program?

  1. #1
    Registered User Dave Jay's Avatar
    Join Date
    Mar 2002
    Posts
    33

    what is wrong with this simple program?

    This is a simple little menu which doesn't work. After a character is inputted, user input is skipped for the next scanf statement if the loop continues. If response is declared to be int, it works, why doesnt this work for char?


    Code:
    #include <stdio.h>
    
    int main()
    {
    char response;
    
      do {
       printf("\nMENU (4 to quit)\n");
       printf(" :");
       scanf("%c",&response);
       
       switch (response) {
         case '1':  printf("case 1 reached\n");               
                    break;
         case '2':  
                    printf("case 2 reached\n");
                    break;
         case '3':  
                    printf("case 3 reached\n");
                    break; 
       }
      } while(response != '4');
    
      return 0;
    
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by Dave Jay
    This is a simple little menu which doesn't work. After a character is inputted, user input is skipped for the next scanf statement if the loop continues. If response is declared to be int, it works, why doesnt this work for char?
    You type "1\n" (the digit one followed by the enter key), right? The '\n' is not equal to '1', '2', '3', or '4'. The input buffer does not need to wait for you to type an answer if there is data ready and waiting.

    http://faq.cprogramming.com/cgi-bin/...&id=1043284392
    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 Dave Jay's Avatar
    Join Date
    Mar 2002
    Posts
    33

    yeah but

    why does the input buffer flush when response is declared as int?

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by Dave Jay
    why does the input buffer flush when response is declared as int?
    Short answer: it doesn't.
    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.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program Plan
    By Programmer_P in forum C++ Programming
    Replies: 0
    Last Post: 05-11-2009, 01:42 AM
  2. Simple Blackjack Program
    By saber1357 in forum C Programming
    Replies: 1
    Last Post: 03-28-2009, 03:19 PM
  3. Replies: 5
    Last Post: 01-13-2007, 02:14 AM
  4. Help with small simple program
    By Sonor in forum C Programming
    Replies: 5
    Last Post: 04-02-2005, 07:40 AM
  5. simple frontend program problem
    By gandalf_bar in forum Linux Programming
    Replies: 16
    Last Post: 04-22-2004, 06:33 AM