themacexpert themacexpert - 4 months ago 41
C Question

Fgets() keeps skipping first character

This is part of a larger program to emulate the cat command in unix. Right now trying to take input and send it to stdout:

char in[1000];
int c = 0;
while ((c = getchar()) != EOF)
fputs(in, stdout);

This sends output to stdout, but in every case it skips the first letter. For instance, if I type the word

I get back:



Your problem is all about eating.

c = getchar()

This line, as many I/O operations in C consume your buffer. Meaning that when you have say 0123456789 after your getchar() you're left with 123456789 in your buffer.

What you want to do is use the same functions to control the input and to store it, so something like getting rid of the getchar() should do the trick :

while (fgets(in,1000,stdin) != NULL)
   fputs(in, stdout);

And there you have it !