Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put A String In A ifstream Method [duplicate]

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!

like image 802
Nathan Campos Avatar asked Aug 03 '26 14:08

Nathan Campos


1 Answers

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 !!!
}
like image 77
Kirill V. Lyadvinsky Avatar answered Aug 06 '26 02:08

Kirill V. Lyadvinsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!