You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

g++编译报错:'gets'不是std成员,求同版本适配解决方法

解决g++ 7.4下std::gets编译报错问题

报错原因

gets函数在C11标准中被标记为废弃,C17标准直接将其从标准库中移除。g++ 7.4默认支持C++17标准,因此编译时会报错找不到std::gets。

解决方法

方法1:使用fgets替代(推荐,安全)

fgets是标准库中安全的行输入函数,需要指定缓冲区大小和输入流,避免缓冲区溢出。示例代码:

#include <stdio.h>
#include <cstring>
using namespace std;

int main()
{
    char ch[100];
    // 从标准输入读取一行,最多读取sizeof(ch)-1个字符
    fgets(ch, sizeof(ch), stdin);
    // 移除fgets读取到的换行符(如果存在)
    ch[strcspn(ch, "\n")] = '\0';
    puts(ch);
    return 0;
}

strcspn用于找到换行符的位置,将其替换为字符串结束符,保证输出和原需求一致。

方法2:使用C++风格的cin.getline

如果更倾向于C++标准库的输入方式,可以用cin.getline,它会自动丢弃换行符:

#include <iostream>
using namespace std;

int main()
{
    char ch[100];
    cin.getline(ch, sizeof(ch));
    cout << ch << endl;
    return 0;
}

方法3:临时降低编译标准(不推荐,不安全)

如果必须使用gets,可以将编译标准降到C11,并移除std::前缀(C11中gets在全局命名空间):
编译命令:

g++ -std=c++11 -o test.out test.cpp

修改后的代码:

#include <stdio.h>
using namespace std;

int main()
{
    char ch[100];
    gets(ch);
    puts(ch);
    return 0;
}

⚠️ 注意:gets函数不检查输入长度,若输入超过缓冲区大小会导致缓冲区溢出,存在严重安全隐患,不建议使用。

内容的提问来源于stack exchange,提问作者Arun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 08:52:52