简体   繁体   English

为什么在我包含 stdio.h 时没有声明“gets()”函数?

[英]Why isn't the "gets()" function declared when I include stdio.h?

#include <stdio.h>

int main() {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return (0);
}

In my code, why isn't the gets() function declared?在我的代码中,为什么没有声明gets()函数? It shows me a bunch of errors such as:它向我展示了一堆错误,例如:

In function ‘int main()’:
 error: ‘gets’ was not declared in this scope
gets(str);
    ^~~~
[Finished in 0.2s with exit code 1]

I want to know why this kind of problem occurs?我想知道为什么会出现这种问题?

gets has not been part of the C language for the past 9 years, and prior to that, was deprecated and extremely unsafe - not just difficult to use in a safe/correct manner, impossible.在过去的 9 年中, gets一直没有成为 C 语言的一部分,在此之前,它已被弃用且极其不安全——不仅难以以安全/正确的方式使用,而且是不可能的。 Whoever taught you C is not fit to be teaching.教你 C 的人不适合教书。

I didn't know gets was deprecated, but you can use fgets .我不知道get已被弃用,但您可以使用fgets https://en.cppreference.com/w/c/io/fgets https://en.cppreference.com/w/c/io/fgets

Where you have to specify the maximum size available in the buffer (which protects against buffer overflow).您必须指定缓冲区中可用的最大大小(防止缓冲区溢出)。

fgets(buffer, sizeOfBuffer, stdin)

Be aware意识到

That fgets also reads the newline character into the buffer while gets doesn't (as mentioned in the comments). fgets还会将换行符读入缓冲区,而get不会(如评论中所述)。 So you have to remove the newline character afterwards if you are not interested in it.因此,如果您对换行符不感兴趣,则必须在之后删除换行符。

I am assuming you are wanting to get keyboard input from the user?我假设您想从用户那里获得键盘输入?

If you are using c++ you can use cin >> str如果您使用的是 C++,则可以使用cin >> str

If you are using c you will want scanf("%s", &str)如果你使用 c 你会想要scanf("%s", &str)

gets was deprecated in C++11 and removed from C++14 gets在 C++11 中被弃用并从 C++14 中删除

gets() has been removed from the C language. gets()已从 C 语言中删除。 This function cannot be used safely because the size of the destination array is not provided, hence a long enough input line will cause undefined behavior as gets() will write beyond the end of the array.由于未提供目标数组的大小,因此无法安全地使用此函数,因此足够长的输入行将导致未定义的行为,因为gets()将写入超出数组末尾的内容。

Here is a replacement function that takes an extra argument:这是一个带有额外参数的替换函数:

#include <stdio.h>

// read a line from stdin, ignore bytes beyond size-1, strip the newline.
char *safe_gets(char *dest, size_t size) {
    int c;
    size_t i = 0;
    while ((c = getc(stdin)) != EOF && c != '\n') {
        if (i + 1 < size)
            dest[i++] = c;
    }
    if (size > 0)
        dest[i] = '\0';
    return (i == 0 && c == EOF) ? NULL : dest;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM