"Sams teach yourself C" 中的示例 使用"fgets"但返回错误
Example from "Sams teach yourself C" Uses "fgets" but returns errors
所包含的代码与书中的示例完全相同,但是它返回错误。这本书有什么地方写错了吗?我以前从未使用过#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()
必须接受三个参数
- 字符串将读取值
- 在该字符串中写入的字节数。但如果您发现
Enter key caracter
,它将在此时停止。 读取数据的流。
这里你只指定了一个参数,所以这是不够的。这就是导致错误的原因。fgets有一个 simplified
版本,它只读取用户输入的数据,它被称为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
正确的格式是:
char * fgets ( char * str, int num, FILE * stream );
所以在你的情况下,它应该是这样的:fgets(buffer,sizeof(buffer),stdin);
您看过有关fgets的文档吗?
http://www.cplusplus.com/reference/cstdio/fgets/也有一个正确使用的例子。
这是过时的代码,因为gets()已被弃用,但要使您的示例正常工作,您可以这样做:
#include <stdio.h>
#include <string.h>
int main(void)
{
char buffer[256];
printf("Enter your name and press <Enter>:");
gets(buffer);
printf("nYour name has %d characters and spaces!n", (int)strlen(buffer));
return 0;
}
玩得开心!
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 为什么使用 "this" 指针调用派生成员函数?
- 如何使用 FGETS 获取文本,并保存 std::string
- 在C++中使用哪个函数来输入多个单词,比如C中的fgets
- 使用 fgets() 从键盘读取时从以前的输入读取换行符
- C++:使用 fgets() 读取字符输入时出错
- 使用 fgets() c++ 读取大型 txt 文件时的 CPU 使用率为 99%
- 当我使用 scanf_s 时我得到 4,但当我使用 fgets() 时得到 1
- 如何使用 fgets 获得整条线
- "Sams teach yourself C" 中的示例 使用"fgets"但返回错误
- 使用select()和fgets()从串行端口访问信息