In C, given a string variable str, which of the following two should be preferred to print it to stdout?
puts() can be preferred for printing a string because it is generally less expensive (implementation of puts() is generally simpler than printf()), and if the string has formatting characters like ‘%’, then printf() would give unexpected results. Also, if str is a user input string, then use of printf() might cause security issues (see this for details).
Also note that puts() moves the cursor to next line. If you do not want the cursor to be moved to next line, then you can use following variation of puts().
You can try following programs for testing the above discussed differences between puts() and printf().
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Nested printf (printf inside printf) in C
- What is use of %n in printf() ?
- Use of & in scanf() but not in printf()
- How to print % using printf()?
- Cin-Cout vs Scanf-Printf
- Passing NULL to printf in C
- Execution of printf with ++ operators
- How to change the output of printf() in main() ?
- Return values of printf() and scanf() in C/C++
- What is the difference between printf, sprintf and fprintf?
- Printing source code of a C program itself
- Print all possible combinations of the string by replacing '$' with any other digit from the string
- Print substring of a given string without using any string function and loop in C
- How to find length of a string without string.h and loop in C?
- Tokenizing a string in C++