Functionality of puts

111 Views Asked by At

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.

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

Your first output has two newlines at the end of the transmitted string, not one, and your second has one, not zero.

In the first output, the first newline ends the “Hello World” line and moves display to the next line. The second newline ends a blank line. If the second newline were not there, then terminal output, such as the prompt printed by your shell, would appear on the line immediately below “Hello World” instead of after a blank line.

In the second output, the newline ends the “Hello World” line and moves display to the next line. If the newline were not here, output would continue on the same line as “Hello World” instead of on the next line.

Your first output contains two newlines because fgets includes in the buffer the newline character it read from the input string and puts adds another newline character.

0
On

fgets will store the trailing newline from your input to the target array if there's room; that's why the results are different.