使用字符串将文件名传递给 fstream

using string to pass filename to fstream

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

我使用以下方法读取 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);