Thread: loops ?

  1. #1
    life is a nightmare
    Join Date
    Apr 2007
    Posts
    127

    loops ?

    hi all
    Code:
    #include <stdio.h>
    main()
    {
          int d;
    
         for(d=0;d<100;d++)
         {
                           printf("&#37;d\n",d);
                           getchar();
                           }
                                            
          exit(EXIT_SUCCESS);
          }
    shouldn't this program ask me for a key press before it execute again?
    here is what i got

    ./count_a
    0
    >a
    1
    2
    3
    >a
    4
    5
    6
    >a refers to my key press
    it's printing about three times before it asks for my key press?
    the question is
    why is that happening?
    thanks in advance

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Because you're pressing 'a' + Enter I presume.

    getchar() is reading the 'a', and then the '\n' is left in the buffer, possibly a '\r' too (I dunno, I'm tired.). When getchar() is called again, it reads the next char in the buffer instead of asking you for input.

  3. #3
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Flush the input stream (stdin), before you ask for input to ensure it's empty (not using fflush, see the FAQ).

    [edit] Dang MacGyver and his powerfingers, I'll have to shoot him with my deathray
    Last edited by zacs7; 06-26-2007 at 06:07 AM.

  4. #4
    life is a nightmare
    Join Date
    Apr 2007
    Posts
    127
    thanks all i think i got it
    thanks again

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Loops Trouble
    By rlframpton in forum C Programming
    Replies: 2
    Last Post: 04-17-2009, 01:08 AM
  2. Too many loops D:
    By F5 Tornado in forum C++ Programming
    Replies: 6
    Last Post: 12-03-2007, 01:18 AM
  3. help with arrays and loops
    By jdiazj1 in forum C Programming
    Replies: 4
    Last Post: 11-24-2001, 04:28 PM
  4. for loops in C
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 10-15-2001, 05:09 PM
  5. exiting loops with ease?
    By KingRuss in forum Game Programming
    Replies: 3
    Last Post: 09-24-2001, 08:46 PM