getchar() and putchar()
Asked Answered
T

4

6

in the example:

#include <stdio.h>

main()
{
    long nc;

    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%ld\n", nc);
}

I don't quite understand it. putchar() would put the character out, but why is it that after EOF it puts all the characters out, and where is it remembering all these characters? Thanks.

Teshatesla answered 2/2, 2010 at 23:46 Comment(3)
Umm... there's no putchar() in this code.Middleaged
What putchar() are you talking about?Inocenciainoculable
I think you posted the wrong program from K&R!Cranach
D
9

It's called buffering and it's done by the operating system. Usually it does line buffering where it just saves every character you put to it in memory, and then writes it all to the file when it encounters a line break. This saves on resources because file operations take much more time than other operations. So instead of doing output with every single character, it waits for a bunch of characters to collect in the buffer and writes them out all in one go.

It's just a clever maneuver done by the OS that you, the programmer, don't need to worry about. Just throw your characters at it one by one and let the OS handle the rest in its own way.

Damnedest answered 2/2, 2010 at 23:56 Comment(1)
Isn’t it done by the standard library, not the OS?Selfemployed
B
2

[This isn't an answer, but you can't put code in the comments]

I think you meant something like this:

#include <stdio.h>

main()
{
    long nc;
    nc = 0;
    char c;
    while ((c = getchar()) != EOF)
    {
       putchar(c); /* prints one char */
        ++nc;
    }
    printf("%ld\n", nc); /* prints the number of characters read */
}
Bethune answered 3/2, 2010 at 3:18 Comment(0)
D
1

No where, this code only empty the input and write how many caracters where left before the flush.

This is to be sure that the is no caracters remaining in the input file (stdin)

Debbi answered 2/2, 2010 at 23:53 Comment(0)
M
1

putchar put the char into the buffer when it comes an enter ,then it will bring the line word output to the screen.

Mohr answered 12/6, 2011 at 11:58 Comment(1)
Thanks! I was also wondering why the characters don't show up on the screen as you type them, despite putchar() in the loop (not in the above code, but in KR's example).Imperceptible

© 2022 - 2024 — McMap. All rights reserved.