Junk in my stdin?

This is a discussion on Junk in my stdin? within the C Programming forums, part of the General Programming Boards category; I'm working on implementing a lexer and I noticed that the first call to getchar() always returns a character of ...

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    87

    Junk in my stdin?

    I'm working on implementing a lexer and I noticed that the first call to getchar() always returns a character of junk before it prompts me for any input. I wrote a small test program to reproduce this:

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main() {
      int c;
    
      for ( ; ; c = getchar()) {
        printf("%c\n", c);
      }
    
      return 0;
    }
    Below is a run of my program:
    Code:
    $ ./getchar_test 
    P
    I didn't write that!
    I
     
    d
    i
    d
    n
    '
    t
     
    w
    r
    i
    t
    e
     
    t
    h
    a
    t
    !
    Is there junk in my stdin? Can I clear it out? Am I just overlooking something obvious? That extra character seems to always be the same per program. For this test, it seems to always be 'P', In my lexer it is character value 0.

    Thanks

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    No. It's because of your (misuse) of the for loop.

    The first iteration will give you the undefined value of "c", that is whatever c happens to be when you run your program. If you don't believe me, initialize c to 0 and see for yourself.

    Otherwise, you probably just want something along the lines of:

    Code:
    while((c = getchar()) != EOF)
    {
       printf("%c\n", c);
    }
    In short,
    Code:
    for ( a; b; c)
    {
       x;
    }
    Is the same as:

    Code:
    a;
    while(b)
    {
       x;
    
       c;
    }
    Last edited by zacs7; 06-21-2009 at 07:14 PM.

  3. #3
    Registered User
    Join Date
    May 2008
    Posts
    87
    Ah of course. I figured it would be something simple, but I've been staring at this screen for too long. I took the idea for the for loop from the "dragon book", but I see they initialized the character to a meaningful value, which I forgot to do.

    Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking stdin for input
    By hawaiian robots in forum C Programming
    Replies: 7
    Last Post: 05-19-2009, 09:06 AM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. Replies: 2
    Last Post: 07-12-2008, 12:00 PM
  4. value of stdin (not zero?)
    By taisao in forum Linux Programming
    Replies: 3
    Last Post: 05-27-2007, 08:14 AM
  5. stdin question
    By oomen3 in forum C Programming
    Replies: 6
    Last Post: 02-19-2003, 01:52 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21