Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fgets() keeps skipping first character

Tags:

c

debugging

fgets

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)
 {
   fgets(in,1000,stdin);
   fputs(in, stdout);
 }

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

I get back:

omputer
like image 363
themacexpert Avatar asked Apr 28 '15 11:04

themacexpert


1 Answers

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 !

like image 135
Mekap Avatar answered Sep 24 '22 12:09

Mekap