Put string in Astream method

I am learning C ++ and I am having problems when I try to use String in the ifstream method, for example:

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

Here is the complete 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 Eclipse, x error 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 puts x in front of this method, which indicates a syntax error, but what is wrong with the syntax? Thanks!

+3
source share
2 answers

You should pass the constructor char*to ifstream, use the function 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 !!!
}
+8
source

, ifstream , c-style:

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

std::string c-style, : c_str().

:

...
ifstream myfile ( file.c_str() );
...
+5

Source: https://habr.com/ru/post/1713145/


All Articles