Put A String In A ifstream Method [duplicate]

匆匆过客 提交于 2021-02-07 22:01:49

问题


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!


回答1:


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



回答2:


The problem is that ifstream's constructor does not accept a string, but a c-style string:

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

And std::string has no implicit conversion to c-style string, but explicit one: c_str().

Use:

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


来源:https://stackoverflow.com/questions/1159100/put-a-string-in-a-ifstream-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!