所包含的代码与书本示例完全不同,但它返回错误。这本书有什么地方做得不对吗?我从来没有使用过#include <string.h>
之前,只有#include <stdio.h>
,但我仍然不知道这三个参数应该是什么。
#include <stdio.h>
#include <string.h>
int main(void)
{
char buffer[256];
printf("Enter your name and press <Enter>:\n");
fgets(buffer);
printf("\nYour name has %d characters and spaces!",
strlen(buffer));
return 0;
}
编译器说
Semantic issue with (fgets( buffer ); - Too few arguments to function call, expected 3, have 1
Format string issue (strlen(buffer)); - Format specifies type 'int' but the argument has type 'unsigned long'
最佳答案
fgets()
必须采用三个参数。
- 要放置读取值的字符串
- 要写入此字符串的字节数。但如果您找到
输入键字符
,此时它将停止。 - 从中读取数据的流。
此处您仅指定一个参数,因此这还不够。这就是导致错误的原因。 fgets 有一个简化
版本,它只读取用户键入的数据,称为 gets()
。
gets(buffer);
但是这个函数是不安全的,因为如果用户输入的字节数超过缓冲区的大小,那么就会出现内存溢出。这就是为什么您应该使用 fgets()
。
像这样:
fgets(buffer, sizeof buffer, stdin);
请注意,我已经传递了值 sizeof buffer
和 stdin
。 sizeof buffer
是为了确保我们不会出现内存溢出。 stdin
是对应键盘的流。然后我们从键盘安全地读取数据,您将获得一个有效的代码。
请参阅此处的引用资料: http://www.cplusplus.com/reference/cstdio/gets/ http://www.cplusplus.com/reference/cstdio/fgets/
如果您有兴趣,还有其他函数可以读取用户输入,例如 scanf()
:http://www.cplusplus.com/reference/cstdio/scanf/?kw=scanf
关于c++ - "Sams teach yourself C"中的示例使用 "fgets"但返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24946562/