字符串作为文件名
Strings as File names
如果我将字符串设置为文件名,它不起作用,我不知道为什么。(我正在使用代码块,它似乎适用于其他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
的标志打开支持。
相关文章:
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 无法创建栅格堆栈,因为我无法连接字符串(dir_name + 文件名)
- 无法打开存储在字符串C++中的文件名
- 字符串作为文件名
- C++搜索文件名指针指向字符串 strcmp 错误
- 使用文件名作为字符串从任意souce .cpp文件中调用函数
- C++ GetModule文件名不会返回正确的字符串
- 使用字符串缓冲区文件名更改OFStream的目录
- 来自其他字符串的输出文件名
- 如何在 tchar 中添加格式化字符串(用于多个文件名等)
- Cpp 预处理器和文件名的基本名称,行号为字符串
- 为什么 fstream.open(文件名) 适用于文字而不是生成的字符串?
- 使用字符串将文件名传递给 fstream
- gengetopt:如何解析没有选项(如文件名)的字符串
- 在cpp中串联字符串和int作为文件名
- 7zip 字符串/流压缩 PHP/C?存档中没有文件名/日期存储.7z每个字节都很重要
- 将文件名转换为c字符串
- c++将文件的路径组合为字符串和文件名
- 适用于短文件名的最佳字符串哈希函数
- 将URL编码为安全的文件名字符串