2014-04-05 89 views
0

我正在使用MinGW Developer Studio和MinGW編譯器。我有一個小程序具有以下功能:錯誤將字符串參數傳遞給fstream.open

void NameFile() 
{ 
ofstream outfile; 
string sFilename = "glatisant.html"; 
outfile.open(sFilename, ofstream::out); 
outfile.close(); 
} 

建設時,/編譯,我得到以下錯誤文本:

main.cpp:43: error: no matching function for call to `std::basic_ofstreamstd::char_traits >::open(std::string&, const std::_Ios_Openmode&)'

fstream:695: note: candidates are: void std::basic_ofstream<_CharT, >_Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = >std::char_traits]

根據fstream.out()的定義,我應該能夠傳遞一個字符串並使其工作,但事實並非如此。爲什麼不?

注意:錯誤消息似乎表明我的編譯器無法識別在C++ 11中定義的字符串類型參數的可能性。我想我需要讓我的環境使用C++ 11,因爲我會真的更喜歡符合現代標準的方法。

回答

1

在非C++ 11,方法ofstream::open需要const char *,所以試圖通過sFilename.c_str()

outfile.open(sFilename.c_str(), ofstream::out); 
         ^^^^^^^^ 

否則在C++ 11你可以通過一個std::string過,請確保您已啓用-std=c++11-std=c++0x

在MingW平臺,開發者工作室你可以轉到項目>設置>編譯並把-std=c++11-std=c++0x

enter image description here

+0

我想C++ 11將是默認的。我如何設置它? –

+0

將'--std = C++ 11'放入make-file或compile命令中。 – deepmax

+0

我會盡快研究;我沒有真正處理makefile,也不確切知道「編譯命令」是指什麼。 –

0

你可能是指ios_base::out而不是ofstream::out「額外編譯選項」。

另外,在C++98/C++03中,ofstream::open的輸入是char const*,而不是std::string

如果使用C++98/C++03,如果您正在使用C++11

outfile.open(sFilename, ofstream::out); 

改變

outfile.open(sFilename.c_str(), ios_base::out); 

,一切都很好。

+0

在C++ 11中,'ofstream :: out'運行良好,所以他不必改變它。見[這裏](http://coliru.stacked-crooked.com/a/ac466093345ec74b) – deepmax

+0

@MM。感謝您指出了這一點。我不知道。 –

相關問題