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
676 views
in Technique[技术] by (71.8m points)

c - putchar() vs printf() - Is there a difference?

I am currently in chapter 1.5.1 File copying and made a program like so:

#include <stdio.h>

/* copy input to output; 1st version */
main()
{
    int c;

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

If I ran it like this:

PS <..loc..> cc copy-0.c
PS ./a
Black
Black
White
White
Gray
Gray

The output is what I input.

And here's a program I made for experimental purposes:

#include <stdio.h>

/* copy input to output; 1st version */
main()
{
    int c;

    c = getchar();
    while (c != EOF) {
        printf("%c",c);
        c = getchar();
    }
}

It produces the same result but is there a difference between putchar and printf?

Which is better to use between the 2?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

printf is a generic printing function that works with 100 different format specifiers and prints the proper result string. putchar, well, puts a character to the screen. That also means that it's probably much faster.

Back to the question: use putchar to print a single character. Again, it's probably much faster.


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

...