Namespaces
Variants

std:: gets

From cppreference.net
< cpp ‎ | io ‎ | c
定义于头文件 <cstdio>
char * gets ( char * str ) ;
(C++11 起弃用)
(C++14 起移除)

stdin 读取字符到指定字符串,直到遇到换行符或到达文件结尾。

目录

参数

str - 要写入的字符串

返回值

str 成功时返回该指针,失败时返回空指针。

若失败是由文件结束条件引起的,则额外设置 eof 指示器(参见 std::feof() )于 stdin 。若失败由其他错误导致,则设置 error 指示器(参见 std::ferror() )于 stdin

注释

std::gets() 函数不会执行边界检查。因此,该函数极易受到缓冲区溢出攻击。它无法安全使用(除非程序运行在可限制 stdin 输入内容的环境中)。基于此原因,该函数在 C++11 中被弃用,并在 C++14 中完全移除。可改用 std::fgets() 作为替代方案。

示例

#include <array>
#include <cstdio>
#include <cstring>
int main()
{
    std::puts("Never use std::gets(). Use std::fgets() instead!");
    std::array<char, 16> buf;
    std::printf("Enter a string:\n>");
    if (std::fgets(buf.data(), buf.size(), stdin))
    {
        const auto len = std::strlen(buf.data());
        std::printf(
            "The input string:\n[%s] is %s and has the length %li characters.\n",
            buf.data(), len + 1 < buf.size() ? "not truncated" : "truncated", len
        );
    }
    else if (std::feof(stdin))
    {
        std::puts("Error: the end of stdin stream has been reached.");
    }
    else if (std::ferror(stdin))
    {
        std::puts("I/O error when reading from stdin.");
    }
    else
    {
        std::puts("Unknown stdin error.");
    }
}

可能的输出:

Never use std::gets(). Use std::fgets() instead!
Enter a string:
>Living on Earth is expensive, but it does include a free trip around the Sun.
The input string:
[Living on Earth] is truncated and has the length 15 characters.

参见

stdin 、文件流或缓冲区读取格式化输入
(函数)
从文件流获取字符串
(函数)
向文件流写入字符串
(函数)
C 文档 关于 gets