簡體   English   中英

將字符串參數傳遞給fstream.open時出錯

[英]error passing string argument to fstream.open

我正在將MinGW Developer Studio與MinGW編譯器一起使用。 我有一個具有以下功能的小程序:

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

在構建/編譯時,出現以下錯誤文本:

main.cpp:43:錯誤:沒有匹配函數可調用`std :: basic_ofstreamstd :: char_traits> :: open(std :: string&,const std :: __ Ios_Openmode&)'

fstream:695:注意:候選者為: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,因為我真的更喜歡使用符合現代標准的方法。

在非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-Developer-Studio中,您可以轉到“項目”>“設置”>“編譯”,然后將-std=c++11-std=c++0x放入“其他編譯選項”

在此處輸入圖片說明

您可能是說ios_base::out而不是ofstream::out

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

如果您使用的是C++98/C++03 ,請更改該行

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

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

如果您使用的是C++11 ,那么一切都很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM