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

后端 未结 5 1646
醉酒成梦
醉酒成梦 2020-12-16 14:50

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

#include 

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


        
相关标签:
5条回答
  • 2020-12-16 15:21

    The difference is that putchar prints one character whereas printf can print a lot more.

    printf("%s\n", "this is a lot longer than one character");
    

    Generally when you print something to the terminal you want to end it with a newline character, '\n'. At the very least for that reason I would suggest using printf as then you can write

    printf("%c\n", c);
    

    instead of

    putchar(c);
    putchar('\n');
    
    0 讨论(0)
  • 2020-12-16 15:27

    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.

    0 讨论(0)
  • 2020-12-16 15:29

    printf lets you format strings in a complicated way, substituting things like integers and floats and other strings.

    getchar and putchar get and put characters

    I can say that printf is more useful in more ways compared to putchar.

    Better look in their respective manual pages ( man 3 printf man 3 putchar ) in terminal

    0 讨论(0)
  • 2020-12-16 15:29
    1. Putchar : prints only a single character on the screen as the syntax tells.
    2. Printf : printf line or word on the screen. Hence when you want to display only one character on the screen the use putchar. To read a string use gets function. To display string you can use puts() or printf both.
    0 讨论(0)
  • 2020-12-16 15:31

    I compiled an example using printf("a") with -S and got call putchar in the assembly code. Looks like when you have only one char in the printf the compiler turns it into a putchar(). I did another example using printf("ab") and got call printf, with the text section in the %edi register.

    0 讨论(0)
提交回复
热议问题