2009-07-21 46 views
3

我学习C++,我得到一些当我试图在一个ifstream的方法使用字符串烦恼,就像这样:把字符串中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; 
} 

这里是Eclipse的错误,X方法前:

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

但是,当我尝试编译在Eclipse它把一个X的方法之前,表示在语法错误,但什么是错的语法?谢谢!

+0

你能提供有关你得到错误信息?或者,也许你可以发布一个完整的样本... – 2009-07-21 13:19:20

+0

也许fstream不包括在内?请提供完整的代码 – CsTamas 2009-07-21 13:22:58

回答

8

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

的问题是,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()); 
...