Frage

    

Diese Frage bereits eine Antwort hier:

    
            
  •              keine passende Funktion - ifstream open ()                                      1 Antwort                          
  •     
    

Ich lerne C ++ und ich habe einige Probleme bekommen, wenn ich zu verwenden, ich versuche ein String in eine ifstream Methode, wie folgt aus:

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

Hier ist der vollständige Code:

// 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;
}

Und hier ist der Fehler der Eclipse, die x , bevor die Methode:

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

Aber wenn ich versuche, in Eclipse zu kompilieren es ausdrückte ein x , bevor das Verfahren, die einen Fehler in der Syntax gibt an, aber was in der Syntax falsch ist? Dank!

War es hilfreich?

Lösung

Sie sollten char* passieren Konstruktor ifstream, verwenden c_str() Funktion.

// 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 !!!
}

Andere Tipps

Das Problem ist, dass ifstream Konstruktor keinen String akzeptiert, aber ein C-String:

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

Und std::string hat keine implizite Konvertierung in C-String, sondern explizit ein. c_str()

Verwendung:

...
ifstream myfile ( file.c_str() );
...
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top