字符串作为文件名

Strings as File names

本文关键字:文件名 字符串      更新时间:2023-10-16

如果我将字符串设置为文件名,它不起作用,我不知道为什么。(我正在使用代码块,它似乎适用于其他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");
}

错误信息:

调用 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重载修复了File.open(FileName)问题。

如果您的编译器不支持 C++11,那么也许您应该获得更新的编译器。或者也许它确实支持 C++11,您只需要使用类似 -std=c++11 的标志打开支持。