Reputation: 13
char s[100]={0};
fgets(s, sizeof(s), stdin);
In the context of the code above, what is the difference between these three?
printf("%s",s);
printf(s);
fputs(s,stdout);
Upvotes: 0
Views: 1346
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
Reputation: 4537
#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
Reputation: 68034
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'
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
fputs(s,stdout); OK. Not as heavy as printf but will add the new line
Upvotes: 3