命名空间
变体
操作

std::gets

来自 cppreference.cn
< cpp‎ | io‎ | c
 
 
 
 
定义于头文件 <cstdio>
char* gets( char* str );
(C++11 中已弃用)
(C++14 中已移除)

stdin 读取字符到给定的字符串,直到遇到换行符或文件结束符。

目录

[编辑] 参数

str - 要写入的字符串

[编辑] 返回值

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

如果失败是由文件结束条件引起的,则还会设置 stdin 上的 eof 指示器(参见 std::feof())。如果失败是由其他错误引起的,则会设置 stdin 上的错误指示器(参见 std::ferror())。

[编辑] 注解

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