Thread: if then else - newbie question

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    4

    if then else - newbie question

    Still learning C, playing with if, then, else. In the program below, the final ELSE statement executes in every WHILE loop. I'm not sure why. Program and output are below. I was thinking that at each getchar() in the WHILE loop, the program would pause, take in the input and then bounce back up to the WHILE evaluation. Thanks for your help.

    Jim

    Code:
    #import <Foundation/Foundation.h>
    
    int main (int argc, const char * argv[])
    {
    	char x;
    	
    	printf("Enter a, b or c (q to quit);\n");
    	x = getchar();
    	
    	while (x != 'q') {
    		if (x=='a') {
    			printf("Menu A\n");
    			x = getchar();
    		}
    		else if (x=='b'){
    			printf("Menu B\n");
    			x = getchar();
    		}
    		else if (x=='c'){
    			printf("Menu C\n");
    			x = getchar();
    		}
    		else {
    			printf("Not a valid option\n");
    			x = getchar();
    		}
    	}
    	
    	return(0);
    }
    And the output is:

    Running…
    Enter a, b or c (q to quit);
    a
    Menu A
    Not a valid option
    b
    Menu B
    Not a valid option
    d
    Not a valid option
    Not a valid option
    q

    Debugger stopped.
    Program exited with status value:0.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Because the enter-key is neither a, nor b, nor c; therefore, when enter-key is read in, the final else switch is done.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Yep. Read this:

    STDIN pitfalls

    Stuff about the "\n" newline from the enter key starts in the 4th paragraph.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Apr 2010
    Posts
    4
    Thanks! That now makes sense.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie question, C #
    By mate222 in forum C# Programming
    Replies: 4
    Last Post: 12-01-2009, 06:24 AM
  2. Stupid Newbie question
    By TimL in forum C++ Programming
    Replies: 4
    Last Post: 07-22-2008, 04:43 AM
  3. C prog newbie question
    By Draginzuzu in forum C Programming
    Replies: 1
    Last Post: 02-03-2003, 06:45 PM
  4. a stupid question from a newbie
    By newcomer in forum C++ Programming
    Replies: 4
    Last Post: 01-11-2003, 04:38 PM
  5. newbie class templates question
    By daysleeper in forum C++ Programming
    Replies: 2
    Last Post: 09-18-2001, 09:50 AM