gets()
的描述:它从系统标准输入设备(通常是键盘)读取一个字符串。由于字符串没有预定义的长度,
gets()
需要一种方法来知道何时停止。其方法是读取字符,直到它达到换行符(\n
)字符,您可以通过按“Enter”键生成该字符。它接收所有到(但不包括)换行符的字符,添加一个空字符(\0
),并将字符串返回给调用程序。我很好奇当
gets()
仅读入换行符时会发生什么。所以我写了这个: 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;
}
这是我与该程序的交互过程:
$ ./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
第二个块是我们感兴趣的地方,当我只按回车键时。
input
在这种情况下到底是什么呢?它似乎不是我的猜测中的任何一个: \0
或\n
或""
。
==
来比较字符串,你需要使用strcmp
函数。(或者你可以使用input[0] == '\n'
和input[0] == '\0'
。) - molbdniloinput == '\0'
应该改为*input == '\0'
。 - David Ranieriinput == '\0'
相当于input == 0
。 - molbdnilogets
已经过时了。 - Jens Gustedtgets(3)
。 - user2371524gets()
的函数了,它已经从C语言中移除。因此,研究该函数的意义有限。请专注于使用和理解fgets()
函数。 - Lundin