In C, given a string variable str, which of the following two should be preferred to print it to stdout?
1) puts(str);
2) printf(str);
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 ‘%s’, 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().
fputs(str, stdout)
You can try following programs for testing the above discussed differences between puts() and print().
Program 1
C
// C program to show the use of puts#include <stdio.h>int main(){ puts("Geeksfor"); puts("Geeks"); getchar(); return 0;} |
Program 2
C
// C program to show the use of fputs and getchar#include <stdio.h>int main(){ fputs("Geeksfor", stdout); fputs("Geeks", stdout); getchar(); return 0;} |
Program 3
C
// C program to show the side effect of using// %s in printf#include <stdio.h>int main(){ // % is intentionally put here to show side effects of // using printf(str) printf("Geek%sforGeek%s"); getchar(); return 0;} |
Program 4
C
// C prgram to show the use of puts#include <stdio.h>int main(){ puts("Geek%sforGeek%s"); getchar(); return 0;} |
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Nested printf (printf inside printf) in C
- How to print % using printf()?
- Return values of printf() and scanf() in C/C++
- What is use of %n in printf() ?
- How to change the output of printf() in main() ?
- Passing NULL to printf in C
- Cin-Cout vs Scanf-Printf
- Execution of printf with ++ operators
- What is the difference between printf, sprintf and fprintf?
- Use of & in scanf() but not in printf()
- Printing source code of a C program itself
- Print substring of a given string without using any string function and loop in C
- Print all possible combinations of the string by replacing '$' with any other digit from the string
- std::string::crbegin() and std::string::crend() in C++ with Examples
- How to find length of a string without string.h and loop in C?
- What is the best way in C to convert a number to a string?
- Convert a floating point number to string in C
- How to split a string in C/C++, Python and Java?
- C++ string class and its applications
- Different methods to reverse a string in C/C++
Improved By : TusharSharma5

