我正在使用以下方法读取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 可以使用函数 std::string::c_str() 生成 C 风格的、以 null 结尾的字符串:
modelStream.open(STRING.c_str(), ios::in);
这实际上在 C++11 中已“修复”,因此如果您使用它,您的原始代码将可以正常工作。
此外,不建议使用全大写的变量名;也不是称为“字符串”的变量。让名称描述含义。
关于c++ - 使用字符串将文件名传递给 fstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13085949/