I am trying to understand how puts function works in standard C. I read that it prints a specified
string to the standard output and appends a newline character to this string. However, I get different outputs for 2 similar C programs.
I tried 2 ways to use it (I will only provide function main):
1.
char s[20];
fgets(s,20,stdin);
puts(s);
char s[20]="Hello World";
puts(s);
In the first case, if my input is Hello World, then in my terminal the output is:
Hello World
(So a newline is appended) In the second case, in my terminal the output is:
Hello World
It seems that in this case no newline character was appended while I expected to have the same output as in case 1. I don't understand why the outputs are not the same. Probably it is because of fgets, but I don't really understand why fgets makes the outputs different.
It seems that the behaviour that's confusing you isn't puts
, but rather fgets
. In the second example, there is a newline character, there just isn't a blank line.
If the parsing of a line in fgets
is stopped by reading a newline character (as opposed to reaching the end-of-file of the input), then that newline character is included in the buffer.
So while in the second example, s
contains "Hello World"
, in the first one it contains "Hello World\n"
.
In both cases puts
behaves the same, appending a newline. In your first example, this leads to two consecutive newlines being printed, which appears as a completely blank line.