10

With the following code, I get the "gets() was not declared in this scope" error:

#include <iostream>
#include <string.h>
using namespace std;

int main()
{

   // string str[]={"I am a boy"};

   string str[20];`

   gets(str);

   cout<<*str;

   return 0;
}
iksemyonov
  • 4,106
  • 1
  • 22
  • 42
Sharif
  • 101
  • 1
  • 1
  • 4
  • 2
    Read the [gets manual](http://linux.die.net/man/3/gets). It tells you which header file needs to be included. But take careful note of what it says near the end: "Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead." – kaylum Feb 07 '16 at 05:48
  • 1
    You might also want to consider [Why is the gets function so dangerous that is should not be used?](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Bo Persson Feb 07 '16 at 10:36

2 Answers2

13

The function std::gets() was deprecated in C++11 and removed completely from C++14.

ThomasMcLeod
  • 7,603
  • 4
  • 42
  • 80
3

As gets() is a C style function, so if you need to include it in your c++ code then you need to include the header file called stdio.h and moreover you can only pass a c style string to gets() function not c++ string class. So after slight modification in your code it becomes:

#include <iostream>
#include <string.h>
#include "stdio.h"
using namespace std;

int main()
{

// string str[]={"I am a boy"};

char str[20];`

 gets(str);

 printf("%s",str);

return 0;
}
kunal_goyal
  • 117
  • 1
  • 8