Error reading string with gets ();

2

I have problems reading a string in c ++.

Since the strings do not have a character limit (they are dynamic), I thought I would read them with gets in the following way:

#include<iostream>
#include<cstdio>

using namespace std;

int main(){
    string Descripcion;

    cout<<"Ingrese la descripcion del Producto: ";
    gets(Descripcion);
    cout<<"La Descripcion del producto es: "<<Descripcion<<endl;

    return 0;
}

But code :: blocks 16.01 tells me:

|10|error: cannot convert 'std::string {aka std::basic_string<char>}' to 'char*' for argument '1' to 'char* gets(char*)'|

Is there a way to read a string without setting limits?

    
asked by José F 15.10.2017 в 02:39
source

1 answer

3

First, your error:

  

char * gets (char *);

gets( ) expects a pointer to string, and you're passing it a std::string . The compiler does not know how to convert the second into the first, and complains.

Another mistake, even more serious:

Nothing else to do

  

man gets

The first thing we found in an adventencia

  

never use this function

The gets( ) function does not check anything ; it is limited to reading and storing. It is so dangerous that, from C11, no longer exists . DO NOT USE IT .

In C ++, to read full lines, you can use the getline( ) function. It is the equivalent in C ++ to what you are trying to do, but with proper memory handling, and using std::string , as it should be: -)

#include <string>
#include <iostream>

using namespace std;

int main(){
  string Descripcion;

  cout << "Ingrese la descripcion del Producto: ";
  getline( cin, Descripcion );
  cout << "La Descripcion del producto es: " << Descripcion << endl;

  return 0;
}
    
answered by 15.10.2017 / 07:08
source