这个问题已经有一个答案在这里:

我在学习C++我得到了一些麻烦的时候我要用 字符串 在一个 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;
}

这里是错误的蚀, x 以前的方法:

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

但是当我尝试汇编在蚀它把一个 x 以前的方法,表示中的一个错误的语法,但是,什么是错误的,在法?谢谢!

有帮助吗?

解决方案

你应该通过 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 !!!
}

其他提示

问题是,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() );
...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top