使用字符串将文件名传递给 fstream
using string to pass filename to fstream
我使用以下方法读取 txt 文件
modelStream.open("file.txt", ios::in);
if (modelStream.fail())
exit(1);
model = new Model(modelStream);
但是我想知道如何将字符串作为参数传递
string STRING;
modelStream.open(STRING, ios::in);
if (modelStream.fail())
exit(1);
model = new Model(modelStream);
有谁知道这是否可能,如果是,我将如何做?
出于遗留原因,C++03 中的iostreams需要 C 样式、以 null 结尾的字符串作为参数,并且不理解std::string
。幸运的是,std::string
可以生成一个 C 样式的、以 null 结尾的字符串,函数std::string::c_str()
:
modelStream.open(STRING.c_str(), ios::in);
这实际上是在 C++11 中"修复"的,所以如果你使用它,你的原始代码将是有效的。
此外,不建议使用全大写的变量名称;也不建议使用名为"string"的变量。使名称描述含义。
只需使用c_str ()
std::string
方法
modelStream.open(STRING.c_str (), ios::in);
标准流不接受标准字符串,只接受 c 字符串!因此,使用 c_str() 传递字符串:
modelStream.open(STRING.c_str(), ios::in);
相关文章:
- 从命令行c++发送文本文件名
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 在fstream期间忽略空行
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 使用fstream对txt文件中的数字进行循环
- 当Microsoft文档仅包含 C# 示例时,如何查找 C++ 包含文件名
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 如何在CPP的给定目录中列出UTF编码的文件名?
- 使 std::fstream 写入文件末尾,但从头开始读取
- 在Visual Studio 2019中保存时ReadDirectoryChangesW文件名的问题
- 为什么当我在 std::string 中打开文件名的 fstream 时出现"no matching function"错误?
- 如何使用 fstream 打印出文件名
- 为什么 fstream.open(文件名) 适用于文字而不是生成的字符串?
- 使用字符串将文件名传递给 fstream
- FSTREAM不创建具有附加到文件名的ASCTIME值的文件
- 我可以在 fstream 中使用字符串变量作为文件名吗?C++
- 即使文件名不正确,我的fstream也总是返回true
- 使用字符串作为文件名与 std::fstream
- 为什么 (i|o)fstream 采用 const char* 参数作为文件名