What is the difference between printf() and puts() in C?

前端 未结 10 2092
长发绾君心
长发绾君心 2020-12-07 07:27

I know you can print with printf() and puts(). I can also see that printf() allows you to interpolate variables and do formatting.

相关标签:
10条回答
  • 2020-12-07 07:35

    puts is the simple choice and adds a new line in the end and printfwrites the output from a formatted string.

    See the documentation for puts and for printf.

    I would recommend to use only printf as this is more consistent than switching method, i.e if you are debbugging it is less painfull to search all printfs than puts and printf. Most times you want to output a variable in your printouts as well, so puts is mostly used in example code.

    0 讨论(0)
  • 2020-12-07 07:40

    the printf() function is used to print both strings and variables to the screen while the puts() function only permits you to print a string only to your screen.

    0 讨论(0)
  • 2020-12-07 07:44

    When comparing puts() and printf(), even though their memory consumption is almost the same, puts() takes more time compared to printf().

    0 讨论(0)
  • 2020-12-07 07:45

    puts is simpler than printf but be aware that the former automatically appends a newline. If that's not what you want, you can fputs your string to stdout or use printf.

    0 讨论(0)
  • 2020-12-07 07:48
    int puts(const char *s);
    

    puts() writes the string s and a trailing newline to stdout.

    int printf(const char *format, ...);
    

    The function printf() writes output to stdout, under the control of a format string that specifies how subsequent arguments are converted for output.

    I'll use this opportunity to ask you to read the documentation.

    0 讨论(0)
  • 2020-12-07 07:50

    In my experience, printf() hauls in more code than puts() regardless of the format string.

    If I don't need the formatting, I don't use printf. However, fwrite to stdout works a lot faster than puts.

    static const char my_text[] = "Using fwrite.\n";
    fwrite(my_text, 1, sizeof(my_text) - sizeof('\0'), stdout);
    

    Note: per comments, '\0' is an integer constant. The correct expression should be sizeof(char) as indicated by the comments.

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