gpt4 book ai didi

c++ - 将字符串参数传递给 fstream.open 时出错

转载 作者:行者123 更新时间:2023-11-28 06:58:21 24 4
gpt4 key购买 nike

我正在使用 MinGW Developer Studio 和 MinGW 编译器。我有一个具有以下功能的小程序:

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,因为我会真的更喜欢符合现代标准的方法。

最佳答案

在非 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 放入“额外的编译选项”

enter image description here

关于c++ - 将字符串参数传递给 fstream.open 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22877304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com