字符串作为文件名

Cas*_*der 0 c++ codeblocks

如果我将字符串设置为文件名,它不起作用,我不知道为什么.(我正在使用代码块,它似乎适用于其他IDE)

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
   string FileName="Test.txt";
   ofstream File;
   File.open(FileName);
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,而下一个会这样做:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
   ofstream File;
   File.open("Test.txt");
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

没有匹配函数来调用std :: basic_ofstream :: open(std :: string&)

有人可以帮助解决这个问题,我无法理解为什么会出现这种错误.

Chr*_*ckl 6

由于在C++标准化早期应该被视为历史事故,C++文件流最初不支持std::string文件名参数,只支持char指针.

这就是为什么像File.open(FileName),有FileName是一个std::string,没有工作,只好写成File.open(FileName.c_str()).

File.open("Test.txt")总是工作,因为通常的数组转换规则允许将"Test.txt"数组视为指向其第一个元素的指针.

C++ 11 File.open(FileName)通过添加std::string重载来解决问题.

如果你的编译器不支持C++ 11,那么也许你应该得到一个更新的.或许它确实支持C++ 11,你只需要用一个标志来打开支持-std=c++11.