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.
- Taking String input with space in C (3 Different Methods)
- std::string class in C++
- Operators in C | Set 1 (Arithmetic Operators)
- Arrays in C Language | Set 2 (Properties)
- Difference between getc(), getchar(), getch() and getche()
- What is the difference between printf, sprintf and fprintf?
- Scansets in C
- CRASH() macro - interpretation
- What is use of %n in printf() ?
- gets() is risky to use!
- C function to Swap strings
- Storage for Strings in C
- What is return type of getchar(), fgetc() and getc() ?
- Return values of printf() and scanf() in C/C++
- How to print % using printf()?