Thread: newbie question: "do while" loop parsing twice?

  1. #1
    Registered User
    Join Date
    Nov 2011
    Location
    Lisbon, Portugal
    Posts
    8

    newbie question: "do while" loop parsing twice?

    Can somebody please explain why I'm getting a double print out of the actions inside the loop (a simple printf() message) every time I enter a character?

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <ctype.h>
    
    main() {
    
      // Only pressing a numerical key will make a system call to clear the screen
    
      char x;
    
      do {
        printf("\nPress any numerical digit to clear the screen:");
        scanf("%c", &x);
      } while ( isdigit(x) == 0 );
    
      system("clear");
    
    
    } // end of main()
    The isdigit() validation seems to be working. What I'm not understanding is why the printf() message appears twice if I enter a character.

    Thanks.

  2. #2
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    When you hit the enter key to signal processing of the keyboard buffer, you are also sending a newline character into the buffer. The second loop is from reading that newline.

    Simple fix in this case is to put a space between the open-quote and the %c. It tells scanf to ignore and discard all leading whitespace.

    Later on, you might find yourself needing to flush the entire buffer, so remember this for later:
    Code:
    while( getchar() != '\n' ) ;

  3. #3
    Registered User
    Join Date
    Nov 2011
    Location
    Lisbon, Portugal
    Posts
    8
    Quote Originally Posted by Tclausex View Post
    When you hit the enter key to signal processing of the keyboard buffer, you are also sending a newline character into the buffer. The second loop is from reading that newline.

    Simple fix in this case is to put a space between the open-quote and the %c. It tells scanf to ignore and discard all leading whitespace.
    Got it!


    Later on, you might find yourself needing to flush the entire buffer, so remember this for later:
    Code:
    while( getchar() != '\n' ) ;
    Nice. I'm really at the beginning, but I'll try to remember when I get to that.
    Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 03-29-2010, 09:07 PM
  2. newbie question: #include <> or ""
    By AMDx64BT in forum C++ Programming
    Replies: 2
    Last Post: 10-18-2009, 03:03 PM
  3. Need "if","for loop",&"else" source codes
    By dn_angel_07 in forum C++ Programming
    Replies: 3
    Last Post: 10-07-2009, 10:01 PM
  4. Replies: 24
    Last Post: 09-06-2006, 06:17 PM