Put A String In A ifstream Method

c++, file-io, ifstream, input, string

Solution

You should pass `char*` to `ifstream` constructor, use `c_str()` function.

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

Problem

I'm learning C++ and i'm getting some troubles when i'm trying to use a String in a ifstream method, like this: ``` string filename; cout << "Enter the name of the file: "; cin >> filename; ifstream file ( filename ); ``` Here is the full 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; } ``` And here is the error of the Eclipse, the x before the method: ``` no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)' ``` But when i try to compile in Eclipse it put an x before the method, that indicates an error in the syntax, but what is wrong in the syntax? Thanks!

Original source

Related problems