I'm currently doing exercises from Stephan Prata book called "C Primer Plus" and I'm on chapter 11 which is all about strings. I have code like this:
#include <stdio.h>
#define SIZE 10
int main (void)
{
char word[SIZE];
int i;
puts("Enter the string(empty string ends the program):");
while (fgets(word, SIZE, stdin) != NULL && word[0] != '\n')
{
i = 0;
while (word[i] != '\n' && word[i] != '\0')
i ;
if (word[i] == '\n')
word[i] = '\0';
else
while (getchar() != '\n')
continue;
printf("%s", word); // function X
}
printf("%s", word); // function Y
return 0;
}
Output looks like this:
Enter the string(empty string ends the program):
Star Wars <- string I entered
Star Wars <- output from function X
<- empty string I entered
And my question is like this: why the printf is working correctly on the line 19, and don't work in line 21?
CodePudding user response:
This is indeed an interesting point about what an empty string is.
On first pass you enter 10 characters : S t a r blank W a r s \n
. fgets
put 9 in the word
buffer followed by the terminating null, and you read the end of line with your getchar
loop. Then you correctly write Star Wars
with no end of line in the printf
at line 19.
If you enter a newline here, fgets
will write 2 characters in word
: the \n
and a terminating null. As word[0]
is '\n'
, the loop exits, and the printf
at line 21 successfully outputs the newline character, giving a blank line on the terminal window.
Things would be more funny if you entered an end of file mark (Ctrld on an Unix-like system, or Ctrlz or F6 on Windows). Because fgets
would not change anything in the word
array, and the printf
of line 21 would repeat the previous value. On my Windows console, it gives:
Enter the string(empty string ends the program):
Star Wars
Star Wars^Z
Star Wars
CodePudding user response:
I excepted that after I write "Star Wars" that string will be put into array, and after I end program by entering the empty string, the "Star Wars" string will still be in that array.
You overlook that by entering the empty string, that string will be put into word
, and exactly that empty string is printed in printf() (function Y).