Поместите строку в метод ifstream

Я изучаю C++, и у меня возникают некоторые проблемы, когда я пытаюсь использовать String в методе ifstream, например:

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, x перед методом:

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

Но когда я пытаюсь скомпилировать в Eclipse, перед методом ставится x, что указывает на ошибку в синтаксисе, но что не так в синтаксисе? Спасибо!


person Nathan Campos    schedule 21.07.2009    source источник
comment
Не могли бы вы предоставить более подробную информацию об ошибке, которую вы получаете? Или, может быть, вы могли бы опубликовать полный образец ...   -  person Paolo Tedesco    schedule 21.07.2009
comment
может fstream не включен? Пожалуйста, предоставьте полный код   -  person CsTamas    schedule 21.07.2009
comment
Вы включили правильные заголовки?   -  person mdec    schedule 21.07.2009


Ответы (2)


Вы должны передать 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 !!!
}
person Kirill V. Lyadvinsky    schedule 21.07.2009

Проблема в том, что конструктор ifstream принимает не строку, а строку в стиле c:

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

И std::string не имеет неявного преобразования в строку в стиле c, но имеет явное: c_str().

Использовать:

...
ifstream myfile ( file.c_str() );
...
person CsTamas    schedule 21.07.2009