0
#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.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
Nived.R.S
  • 21
  • 4
  • 2
    Does this answer your question? ["gets() was not declared in this scope" error](https://stackoverflow.com/questions/35250198/gets-was-not-declared-in-this-scope-error) – 273K Feb 06 '20 at 15:30
  • @FrançoisAndrieux we still close it as a duplicate, but we don't delete it. How is this question/answer better than the duplicate? Seems like an exact copy to me. – Aykhan Hagverdili Feb 06 '20 at 15:38
  • 1
    My issue with the dupe is they are doing `gets(str);` where `str` is `string str[20]` which will never work. In this case the code "should" work since the types are right. – NathanOliver Feb 06 '20 at 15:42
  • 1
    @Ayxan The duplicate question has typos and unrelated problems in the code shown. This one is more focused. Additionally, the answer below seems clearer to me than the ones to the duplicate. Edit : I'm wondering if it's permissible to close the older question as a duplicate of this one. – François Andrieux Feb 06 '20 at 15:55
  • @FrançoisAndrieux The advice on meta is to make target the best Q&A. If that means closing an older question to a newer one, that's fine. – NathanOliver Feb 06 '20 at 16:01

3 Answers3

6

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);
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
3

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';

    //...
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You can use scanf() to input string.

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

using namespace std;

int main()
{
    char str[30];
    scanf("%s", str);
}