Frage

I'm working through "The C Programming Language" by K&R and example 1.5 has stumped me:

#include <stdio.h>

/* copy input to output; 1st version */
int main(int argc, char *argv[])
{
    int c;

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

    return 0;
}

I understand that 'getchar()' takes a character for 'putchar()' to display. However, when I run the program in terminal, why is it that I can pass an entire line of characters for 'putchar()' to display?

War es hilfreich?

Lösung

Because your terminal is line-buffered. getchar() and putchar() still only work on single characters but the terminal waits with submitting the characters to the program until you've entered a whole line. Then getchar() gets the character from that buffer one-by-one and putchar() displays them one-by-one.

Addition: that the terminal is line-buffered means that it submits input to the program when a newline character is encountered. It is usually more efficient to submit blocks of data instead of one character at a time. It also offers the user a chance to edit the line before pressing enter.

Note: Line buffering can be turned off by disabling canonical mode for the terminal and calling setbuf with NULL on stdin.

Andere Tipps

Yeah you can actually write whatever you want as long as it's not an EOF char, the keyboard is a special I/O device, it works directly through the BIOS and the characters typed on the keyboard are directly inserted in a buffer this buffer is, in your case read by the primitive getchar(), when typing a sentence you are pushing data to the buffer, and the getchar() function is in an infinite loop, this is why this works.

You can ask me more questions if you want more details about how the IO device work.

Cheers.

Consider the following program,

This program gets the input (getchar runs) till we enter '$' character and prints the output.

#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != '$') 
    putchar(c);
return 0;
}

If we enter input as abcd$$$$$$[Enter], it stores the input in buffer till the last $ symbol. After we pressed enter, the program (while loop) starts to run and getchar function receives one character at a time and prints it, from 'a' till first '$' . And the program won't end till we press '$' in the input.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top