1

it's a very simple question, how to echo every char that I type in stdin to stdout? I'm trying to do it for a long time and I've tried many ways and no one works well. The best I could do was to get what I typed after application end.

The best I did was:

#include <stdio.h>

int main()
{
    while (1)
    {
        int ch = getc(stdin);

        if(ch == EOF) break;

        putc(ch, stdout);
    }
    return 0;
}

Thanks.

Leandro Lima
  • 1,140
  • 3
  • 24
  • 42

3 Answers3

2

You need to flush the stdout:

int main()
{
    while (1)
    {
        int ch = getc(stdin);
        fflush(stdout);
        if(ch == EOF) break;

        putc(ch, stdout);
    }
    return 0;
}
jh314
  • 27,144
  • 16
  • 62
  • 82
  • I don't think I believe this could have done anything to address the problem. But, it may be the case that I just totally did not understand the problem in the first place. – jxh Jul 12 '13 at 02:37
0

The code you have should work just fine, as long as you hit . In most systems, the program will get input in a line oriented fashion. If you want to echo the key immediately after it is hit, you will need to change the input method for the program. On many systems, this would be getch(), but there may be other requirements you have to satisfy before you can use the interface (ncurses requires some additional setup, for example).

When echoing the data immediately after the key is hit, you will be required to flush the output in some way. If you are sending the output to stdout, then a call to fflush() will work. If you are using some system specific output command, you may be required to call some kind or window refresh routine.

jxh
  • 69,070
  • 8
  • 110
  • 193
0

I wonder if a better way would be:

int ch;
while((ch = getchar()) >= 0)
{
    putchar(ch);
}

Then if you call this:

echo this is my input | ./myprogram

it would output the entire stdin this is my input without hitting the enter key.

joshmcode
  • 3,471
  • 1
  • 35
  • 50