2016-04-24 99 views

回答

3

你似乎是用C++,其中std::ifstream::open只接受const char *,舊版本的不是std::string(見docs):

void open (const char* filename, ios_base::openmode mode = ios_base::in); 

正如你所看到的,你不能傳遞std::string這裏。

在C++ 11和更新,你可以傳遞一個std::string還有:

void open (const string& filename, ios_base::openmode mode = ios_base::in); 

更好的方法:使用std::string輸入文件名和做File.open(filename.c_str());打開該文件。

2

該建議基本上是錯誤的。它試圖解決的問題是,在過去的時代,文件流花費了const char*作爲文件名的參數,因此您不能直接使用std::string作爲名稱。當然,這個問題的答案是使用std::string,並調用c_str()通過文件名:

std::string name = "test.txt"; 
std::ofstream out(name.c_str()); 

這些天來,文件流也有一個構造函數std::string,所以你可以這樣做:

std::string name = "test.txt"; 
std::ofstream out(name); 
2

我懷疑是因爲ifstream::open(const char*)的原型。就個人而言,我會寫的代碼爲:

string filename; 
    cin >> filename; 
    ifstream testmarks; 
    testmarks.open(filename.c_str()); 

但是,這又是複雜性來解釋,而這顯然是針對某人非常新的C++。

1

這是錯誤的,這是編寫容易受緩衝區溢出影響的程序的一種很好的方式,至少在本例中是這樣寫的。

0

「打開」函數期望字符指針。

但是它是好的做到這一點:

std::string filename; 
std::cin >> filename; 

std::ifsteam f; 
f.open(filename.c_str()); 
相關問題