Here's the description of gets()
from Prata's C Primer Plus:
It gets a string from your system's standard input device, normally your keyboard. Because a string has no predetermined length,
gets()
needs a way to know when to stop. Its method is to read characters until it reaches a newline (\n
) character, which you generate by pressing the Enter key. It takes all the characters up to (but not including) the newline, tacks on a null character (\0
), and gives the string to the calling program.
It got my curious as to what would happen when gets()
reads in just a newline. So I wrote this:
int main(void)
{
char input[100];
while(gets(input))
{
printf("This is the input as a string: %s\n", input);
printf("Is it the string end character? %d\n", input == '\0');
printf("Is it a newline string? %d\n", input == "\n");
printf("Is it the empty string? %d\n", input == "");
}
return 0;
}
Here's my interaction with the program:
$ ./a.out
This is some string
This is the input as a string: This is some string
Is it the string end character? 0
Is it a newline string? 0
Is it the empty string? 0
This is the input as a string:
Is it the string end character? 0
Is it a newline string? 0
Is it the empty string? 0
The second block is really the thing of interest, when all I press is enter. What exactly is input
in that case? It doesn't seem to be any of my guesses of: \0
or \n
or ""
.