2012-11-01 62 views
2

我從C++獲得了這段代碼,但是我不知道爲什麼添加了「std :: string()」。用輸入名稱打開文件

std::ifstream File; 
std::stringstream FileName; 
FileName << Name; //Name being a string that has been passed as an input to the function. 
       // Eg."MyFile" 
newFileName << ".txt"; //"MyFile.txt" 

File.open(std::string(FileName.str()).c_str(), std::ios::in | std::ios::binary); 

我的問題是,既然STR()返回一個字符串,並c_str()獲得一個字符串並將其轉換爲C字符串,爲什麼我們需要把它的「字符串()」內?難道它不會寫成:

File.open((FileName.str()).c_str(), std::ios::in | std::ios::binary); 
+0

std :: string()創建另一個臨時字符串對象,這是不必要的。 – YaleCheung

回答

1

是的,它可以這樣寫。

使用

std::string(FileName.str()) 

絕對是毫無意義的。

+0

所以我寫的很好,儘管我沒有「using namespace std;」包含在我的文件中,對嗎?感謝您的快速回答! – Mulan

+0

@木蘭 - 是的,沒關係,因爲在這種情況下玩具不需要訪問這個名稱,只需使用'.str()'即可。 –