c - "File Copying" section in K&R -
i'm new programming , can't seem head around why following happens in code, is:
#include <stdio.h> /*copy input output; 1st version */ main() { int c; c = getchar(); while (c != eof) { putchar(c); c = getchar(); } }
so after doing reading, i've gathered following:
- nothing executes until hit enter
getchar()
holding function. - before hit enter, keystrokes stored in buffer
- when
getchar()
called upon, goes looks @ first value in buffer, becomes value, , removes value buffer.
my question when remove first c = getchar()
resulting piece of code has same functionality original code, albeit before type smiley face symbol appears on screen. why happen? because putchar(c)
doesn't hold code, , tries display c
, isn't yet defined, hence outputs random symbol? i'm using code::blocks if helps.
the function listed echo every character type @ it. true i/o "buffered". keyboard input driver of operating system doing buffering. while it's buffering keys press, echoes each key @ you. when press newline driver passes buffered characters along program , getchar
sees them.
as written, function should work fine:
c = getchar(); // (buffer) first char while (c != eof) { // while user has not typed ^d (eof) putchar(c); // put character retrieved c = getchar(); // next character }
because of keyboard driver buffering, echo every time press newline or exit ^d (eof).
the smiley face coming @yuhao described: might missing first getchar
in ran, putchar
echoing junk. 0, looks smiley on screen.
Comments
Post a Comment