Domanda

    

Questa domanda ha già una risposta qui:

         

Sto imparando C ++ e sto ottenendo alcuni problemi quando sto cercando di usare un Stringa in ifstream metodo, in questo modo:

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

Ecco il codice 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;
}

E qui è l'errore di Eclipse, il x prima del metodo:

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

Ma quando provo a compilare in Eclipse ha messo un x prima che il metodo, che indica un errore nella sintassi, ma ciò che è sbagliato nella sintassi? Grazie!

È stato utile?

Soluzione

Si dovrebbe passare a char* ifstream costruttore, utilizzare la funzione 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 !!!
}

Altri suggerimenti

Il problema è che il costruttore di ifstream non accetta una stringa, ma una stringa in stile C:

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

E std::string non ha alcuna conversione implicita a stringa in stile C, ma esplicito uno:. c_str()

Usa:

...
ifstream myfile ( file.c_str() );
...
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top