c++ - "Sams teach yourself C"中的示例使用 "fgets"但返回错误

标签 c++ c compilation fgets

所包含的代码与书本示例完全不同,但它返回错误。这本书有什么地方做得不对吗?我从来没有使用过#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() 必须采用三个参数。

  1. 要放置读取值的字符串
  2. 要写入此字符串的字节数。但如果您找到输入键字符,此时它将停止。
  3. 从中读取数据的流。

此处您仅指定一个参数,因此这还不够。这就是导致错误的原因。 fgets 有一个简化版本,它只读取用户键入的数据,称为 gets()

gets(buffer);

但是这个函数是不安全的,因为如果用户输入的字节数超过缓冲区的大小,那么就会出现内存溢出。这就是为什么您应该使用 fgets()

像这样:

fgets(buffer, sizeof buffer, stdin);

请注意,我已经传递了值 sizeof bufferstdinsizeof 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/

相关文章:

c++ - malloc 没有按我的预期工作

c - 逐个字符打印字符串

c++ - 对 C++ #include 感到困惑

c - bsearch 返回 NULL 但该元素在数组中

c - 为什么 memchr() 将 void 指针作为输入?

linux - 操作系统检测 Makefile

cmake - 如何使用现代 CMAKE(每个目标)添加多个 CUDA gencode?

c++ - C++中使用命名空间的关键字

c++ - 如何在类里面正确使用 boost channel (和光纤)?

C++ 取消引用字符指针(图像数组)非常慢