如果我将字符串设置为文件名,它不起作用,我也不知道为什么。 (我正在使用 codeblocks,它似乎适用于其他 IDE)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string FileName="Test.txt";
ofstream File;
File.open(FileName);
}
这行不通,而下一个行:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream File;
File.open("Test.txt");
}
错误信息:
no matching function for call to std::basic_ofstream::open(std::string&)
谁能帮我解决这个问题,我不明白为什么会出现这个错误。
最佳答案
由于在C++标准化早期应该算是一个历史事故,C++文件流最初不支持std::string
作为文件名参数,只支持char
指针。
这就是为什么像 File.open(FileName)
这样的东西,FileName
是一个 std::string
,没有工作并且有写成 File.open(FileName.c_str())
。
File.open("Test.txt")
始终有效,因为通常的数组转换规则允许将 "Test.txt"
数组视为指向其第一个元素的指针。
C++11 通过添加 std::string
overloads 修复了 File.open(FileName)
问题.
如果您的编译器不支持 C++11,那么也许您应该换一个更新的编译器。或者它可能确实支持 C++11,您只需使用 -std=c++11
之类的标志打开支持。
关于c++ - 字符串作为文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48284348/