Thread: scanf in a loop

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    2

    scanf in a loop

    the first iteration of the loop works fine. then, it comes back around and asks the user to enter in a command but does not implement scanf(). can someone pls tell me how to fix this?
    Code:
    loop:
           
            
    printf("enter command:");
    scanf("%c",&x)
    
    switch(x){
              case 'o':
                   printf("open");
                   goto loop;
              case 'b':
                   printf("boost");
                  goto loop;
              case 'q':
                   printf("quit");  
                 goto loop;
    }
    Last edited by santos288; 10-12-2005 at 08:27 PM. Reason: typo in title

  2. #2
    ---
    Join Date
    May 2004
    Posts
    1,379
    Do yourself a favour and don't use gotos especially for a loop that is so simple

    The reason why scanf doesn't seem to work the second time around is because the '\n' character is left in the buffer. You need to clear the buffer after using it or use a different method like getchar() or fgets()

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    2
    thx for your help

    i tried getchar, but im getting the same problem. how do i clear the buffer?

  4. #4
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Read this FAQ.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stopping an Infinite Loop
    By linuxpyro in forum C Programming
    Replies: 4
    Last Post: 11-30-2006, 12:21 PM
  2. Help with a simple loop...
    By Optimus Prime in forum C Programming
    Replies: 18
    Last Post: 11-11-2006, 09:28 AM
  3. I can't get out of my while loop!!
    By panfilero in forum C Programming
    Replies: 2
    Last Post: 11-20-2005, 04:52 AM
  4. Caught in a Loop
    By aprilbiz in forum C Programming
    Replies: 16
    Last Post: 07-22-2002, 06:06 PM
  5. How to change recursive loop to non recursive loop
    By ooosawaddee3 in forum C Programming
    Replies: 1
    Last Post: 06-24-2002, 08:15 AM