gpt4 book ai didi

c - C11 中的 gets() 等价物是什么?

转载 作者:太空狗 更新时间:2023-10-29 16:28:34 24 4
gpt4 key购买 nike

来自 cplusplus.com

The most recent revision of the C standard (2011) has definitively removed this function from its specification

The function is deprecated in C++ (as of 2011 standard, which follows C99+TC3).

我只是想知道 C11 标准中 gets() 的替代方法是什么?

最佳答案

在 C11 中,gets 已替换为具有以下声明的 gets_s:

char *gets_s(char *str, rsize_t n);

此函数将从stdin 读取最多n-1 个字符到*str。这是为了避免 gets 固有的缓冲区溢出漏洞。函数 fgets 也是一个选项。来自 http://en.cppreference.com/w/c/io/gets :

The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard. fgets() and gets_s() are the recommended replacements.

Never use gets().

鉴于 gets_s 是在标准的扩展中定义的,只能选择性地实现,您可能应该改用 fgets 编写程序。如果您在 stdin 上使用 fgets,您的程序也将在早期版本的 C 中编译。但请记住行为上的差异:当 gets_s已读取 n-1 个字符它会一直读取直到到达新行或文件末尾,然后丢弃输入。因此,使用 gets_s,您总是读取整行,即使输入缓冲区中只能返回其中的一部分。

关于c - C11 中的 gets() 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12893774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com