gpt4 book ai didi

c - 用 fgets 读取输入?

转载 作者:行者123 更新时间:2023-11-30 14:19:50 26 4
gpt4 key购买 nike

我正在尝试使用 fgets() 获取一个字符的输入。据我所知,除非没有空间,否则 fgets 会将\n 添加到输入的末尾。

char test[1];
fgets(test,1,stdin);
readRestOfLine();
while (strcmp(test,"z") != 0){
......
......
}

无论如何,即使输入 z,循环也不会运行。这是为什么?

最佳答案

man fgets

char *fgets(char *s, int size, FILE *stream);

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s... A terminating null byte ('\0') is stored after the last character in the buffer.

size 1 的情况下,这意味着 fgets() 读取为零,即。 e.否,字符并将终止符 '\0' 存储在 test[0] 中。

关于c - 用 fgets 读取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22908483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com