6

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
Steve
  • 1,553
  • 2
  • 20
  • 29
themacexpert
  • 83
  • 2
  • 5

4 Answers4

8

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 !

Mekap
  • 2,065
  • 14
  • 26
6

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);
}
myaut
  • 11,174
  • 2
  • 30
  • 62
4

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)  
haccks
  • 104,019
  • 25
  • 176
  • 264
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

This will work too:

char in[1000];
while ((in[0] = (char)getchar()) != EOF)
 {
   fgets(in+1,999,stdin);
   fputs(in, stdout);
 }
Jahid
  • 21,542
  • 10
  • 90
  • 108
  • If `getchar()` returns 255, then with signed `char`, `in[0]` would have the value of `-1`. This may match `EOF` even though end-of-file did not occur. – chux - Reinstate Monica Apr 28 '15 at 14:12
  • How do you make `getchar()` return 255? – Jahid Apr 28 '15 at 14:37
  • Many ways. Example: 1) `FILE * f= fopen("test.txt", "w"); fputc(255, f); fclose(f):` Now pipe that file into you program "a.bin < text.txt" 2) On many PC keyboard using standard IO: key down, key up. 3) `getchar()`, by spec, returns an `int` in the range of `unsigned char` or `EOF`. It does not specify it will not return 255 - so code should be prepared to handle all 257 different values. – chux - Reinstate Monica Apr 28 '15 at 14:48