Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

c - I'm trying to understand getchar() != EOF

I'm reading The C Programming Language and have understood everything so far. However when I came across the getchar() and putchar(), I failed to understand what is their use, and more specifically, what the following code does.

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

I understand the main() function, the declaration of the integer c and the while loop. Yet I'm confused about the condition inside of the while loop. What is the input in this C code, and what is the output.

Sorry if this is a basic and stupid question, but I'm just looking for a simple explanation before I move on in the book and become more confused.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This code can be written more clearly as:

main()
{
    int c;
    while (1) {
        c = getchar();            // Get one character from the input
        if (c == EOF) { break; }  // Exit the loop if we receive EOF ("end of file")
        putchar(c);               // Put the character to the output
    }
}

The EOF character is received when there is no more input. The name makes more sense in the case where the input is being read from a real file, rather than user input (which is a special case of a file).


[As an aside, generally the main function should be written as int main(void).]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...