why g++ shows “gets()” not declared ,even after including <cstdio>

让人想犯罪 __ 提交于 2020-02-16 08:39:32

问题


#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char str[30];
    gets(str);
}

when i use gets () function compiler gives me the following error

error: 'gets' was not declared in this scope

i was using G++ with geany ide

please make the solution simple cuz iam a beginner.


回答1:


gets was deprecated in C++11 and removed from C++14. If you are using GCC6.0 or newer then by default it uses C++14 and won't be available. Instead of using

main()
{
    char str[30];
    gets(str);
}

use

int main()
{
    std::string str;
    std::getline(cin, str);
}



回答2:


gets is an unsafe function and is not supported by the C Standard any more.

Instead use fgets.

For example

#include <iostream>
#include <cstdio>
#include <cstring>

int main()
{
    char str[30];

    std::fgets(str, sizeof( str ), stdin );

    str[ std::strcspn( str, "\n" ) ] = '\0';

    //...
}


来源:https://stackoverflow.com/questions/60098426/why-g-shows-gets-not-declared-even-after-including-cstdio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!