themacexpert
themacexpert

Reputation: 83

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)
 {
   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

Upvotes: 6

Views: 6134

Answers (4)

Mekap
Mekap

Reputation: 2085

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 !

Upvotes: 8

Jahid
Jahid

Reputation: 22428

This will work too:

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

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

It's not skipping anything you are consuming it with getchar().

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

Change this

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

to

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

Upvotes: 4

myaut
myaut

Reputation: 11494

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

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

But as other answerers note, cleaner way to do that is to use fgets() directly:

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

The third option is to save first character directly to a string:

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

Upvotes: 6

Related Questions