user317427
user317427

Reputation: 13

What is the difference between printf("%s"), printf(s) and fputs?

char s[100]={0};
fgets(s, sizeof(s), stdin);

In the context of the code above, what is the difference between these three?

  1. printf("%s",s);
  2. printf(s);
  3. fputs(s,stdout);

Upvotes: 0

Views: 1346

Answers (3)

PhoenixBlue
PhoenixBlue

Reputation: 1037

As mentioned by other comments and answers, do not try the second option. Also, the third one is quite lighter than the first one.

However, I still prefer the first option (printf() function) because it allows you to have a formatted string, which means you can print out almost any data type using this function, whereas the function fputs only accept strings. So in most cases, you will have to format the string first (maybe using sprintf()) before passing it to the function !

Upvotes: 0

#2 Should NEVER be used. I won't even write it here. An evil input can do very bad things in your system by introducing special characters. New versions of gcc warn you about this bug.

The difference between printf("%s", s); and puts(s) is that puts will add a newline, just like if you called printf("%s\n", s);

Upvotes: 2

0___________
0___________

Reputation: 68034

  1. printf("%s",s); correct but printf is a very heavy function and most compilers will actually replace it with puts in the compiler code if the format string ends with '\n'

  2. printf(s); very dangerous as the format string may contain % and then it will expect another parameters. If it happens it is UB. It also makes your code exploit prone

  3. fputs(s,stdout); OK. Not as heavy as printf but will add the new line

Upvotes: 3

Related Questions