Pregunta

    

Esta pregunta ya tiene una respuesta aquí:

         

Estoy aprendiendo C ++ y me estoy poniendo algunas dificultades cuando estoy tratando de utilizar un Cadena en un ifstream método, como esto:

string filename;
cout << "Enter the name of the file: ";
   cin >> filename;
ifstream file ( filename );

Aquí está el código completo:

// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;

int main ( int argc, char** argv )
{
    string file;
    long begin,end;
    cout << "Enter the name of the file: ";
       cin >> file;
    ifstream myfile ( file );
    begin = myfile.tellg();
    myfile.seekg (0, ios::end);
    end = myfile.tellg();
    myfile.close();
    cout << "File size is: " << (end-begin) << " Bytes.\n";

    return 0;
}

Y aquí es el error del Eclipse, la X antes de que el método:

no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)'

Pero cuando intento compilar en Eclipse se puso x antes del método, que indica un error en la sintaxis, pero lo que está mal en la sintaxis? Gracias!

¿Fue útil?

Solución

Debe pasar a char* ifstream constructor, utilice la función c_str().

// includes !!!
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() 
{   
  string filename;
  cout << "Enter the name of the file: ";
  cin >> filename;
  ifstream file ( filename.c_str() );    // c_str !!!
}

Otros consejos

El problema es que el constructor de ifstream no acepta una cadena, sino una secuencia de c-style:

explicit ifstream::ifstream ( const char * filename, ios_base::openmode mode = ios_base::in );

Y std::string tiene ninguna conversión implícita a la secuencia de c-estilo, pero uno explícita:. c_str()

Uso:

...
ifstream myfile ( file.c_str() );
...
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top