2009-07-21 38 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()); 
...