質問

この質問にはすでに答えがあります:

私は C++ を学んでいますが、C++ を使用しようとすると問題が発生します。 イフストリーム このようなメソッド:

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

完全なコードは次のとおりです。

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

そして、これが Eclipse のエラーです。 バツ メソッドの前:

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

しかし、Eclipseでコンパイルしようとすると、 バツ メソッドの前にこれは構文のエラーを示していますが、構文の何が間違っているのでしょうか?ありがとう!

役に立ちましたか?

解決

あなたは、コンストラクタをchar* ifstream機能を使用するために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 !!!
}

他のヒント

問題ははifstreamのコンストラクタは、文字列が、Cスタイルの文字列を受け付けないということです。

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

そしてstd::stringはCスタイルの文字列への暗黙的な変換はありませんが、明示的な1:c_str()

使用します。

...
ifstream myfile ( file.c_str() );
...
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top