Click to See Complete Forum and Search --> : C I/O problem


Devil
04-01-2002, 08:02 PM
can someone please explane how this code works.?


#include <stdio.h>

/* copy input to output */

main()
{
int c;

c = getchar();

while(c != EOF)
{
putchar(c);
c = getchar();
}

return 0;
}



it seems to enter the while loop without me pressing return.
If so why dosen't it print anything when it goes through the loop.

I seem to be having big problems understanding this simple scrap of code. I just don't get it why it enters the loop but dosen't do everything until you hit return. I also don't get how it can continue from the getchar() function without me pressing return.?

explenation needed...

Strike
04-01-2002, 08:40 PM
It waits for me to enter something to go into the loop for me ...

The only sticking point here I might warn you about is buffered I/O. putchar() and getchar() don't flush the buffers unless you put a newline, I don't think.

sans-hubris
04-01-2002, 09:06 PM
Originally posted by Strike:
<STRONG>It waits for me to enter something to go into the loop for me ...

The only sticking point here I might warn you about is buffered I/O. putchar() and getchar() don't flush the buffers unless you put a newline, I don't think.</STRONG>
It's not just that. Unless you're using the curses library, your program essentially pauses completely when it expects input. It doesn't matter if it's supposed to do anything while you enter something. Your program won't see any input until the user hits enter.

TheLinuxDuck
04-02-2002, 10:21 AM
Originally posted by sans-hubris:
<STRONG>It's not just that. Unless you're using the curses library, your program essentially pauses completely when it expects input. It doesn't matter if it's supposed to do anything while you enter something. Your program won't see any input until the user hits enter.</STRONG>

That's what buffered I/O is.. (^=

There are two ways that I know to set unbuffered input. One is to use ncurses, of which I am not a fan, or the other is to use termios to adjust the terminal settings. An example of the latter can be found here (http://www.codeexamples.org/index.cgi?newBody=c2h/hl.cgi?filename=userinput.c).

Wonk.