-
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
-
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;
}
-
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.