Fgets () continues to skip the first character

This is part of a larger program to emulate the cat command on unix. Right now, trying to accept input and send it to standard output:

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

Sends output to stdout, but in each case it skips the first letter. For example, if I type Computer

I'm coming back:

 omputer 
+5
source share
4 answers

Your problem is food.

 c = getchar() 

This line, since many I / O operations in C consume your buffer . This means that when you said 0123456789 after your getchar() , you will remain with 123456789 in your buffer.

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

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

And here you have it!

+8
source

There is an ungetc function that allows you to return a character to a stream. This is not a standard C function, but implemented on Unix-like systems and Visual Studio CRT:

 while ((c = getchar()) != EOF) { ungetc(c, stdin); fgets(in, 1000, stdin); fputs(in, stdout); } 

But, as other responders point out, a cleaner way to do this is to use fgets() directly:

 while (fgets(in, sizeof(in), stdin) != NULL) 

The third option is to save the first character directly in the line:

 while ((c = getchar()) != EOF) { in[0] = c; fgets(in + 1, 999, stdin); fputs(in, stdout); } 
+6
source

It does not skip anything you consume with getchar() .

Upon successful completion, fgets() returns the string in . If the stream is at the end of the file, the end-of-file indicator for the stream must be set, and fgets() must return a NULL pointer.

Change it

 while ((c = getchar()) != EOF) 

to

 while (fgets(in, sizeof(in), stdin) != NULL) 
+4
source

This will work too:

 char in[1000]; while ((in[0] = (char)getchar()) != EOF) { fgets(in+1,999,stdin); fputs(in, stdout); } 
0
source

All Articles