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

Example from "Sams teach yourself C" Uses "fgets" but returns errors

本文关键字:使用 fgets 错误 返回 teach Sams yourself      更新时间:2023-10-16

所包含的代码与书中的示例完全相同,但是它返回错误。这本书有什么地方写错了吗?我以前从未使用过#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. 在该字符串中写入的字节数。但如果您发现 Enter key caracter ,它将在此时停止。
  3. 读取数据的流。

这里你只指定了一个参数,所以这是不够的。这就是导致错误的原因。fgets有一个 simplified 版本,它只读取用户输入的数据,它被称为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

正确的格式是:

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;
}

玩得开心!