使用字符串传递文件名到fstream [英] using string to pass filename to fstream
问题描述
我使用以下方法读取txt文件
modelStream.open(file.txt,ios: :在);
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 / code>: modelStream.open(STRING.c_str(),ios :: in);
这在C ++ 11中实际上是fixed,所以如果你使用它原来的代码
此外,不建议使用全帽变量名称;也不是称为字符串的变量。使名称描述意义。
I am using the following method to read a txt file
modelStream.open("file.txt", ios::in);
if (modelStream.fail())
exit(1);
model = new Model(modelStream);
but i want to know how i can pass in a string as a parameter
string STRING;
modelStream.open(STRING, ios::in);
if (modelStream.fail())
exit(1);
model = new Model(modelStream);
does anyone know if this is possible and if it is how would I do it?
解决方案 For legacy reasons, iostreams in C++03 expects a C-style, null-terminated string as argument and doesn't understand std::string
. Fortunately, std::string
can produce a C-style, null-terminated string, with the function std::string::c_str()
:
modelStream.open(STRING.c_str(), ios::in);
This was actually "fixed" in C++11, so if you were using it your original code would be functional.
Also, an all-caps variable name is not recommended; neither is a variable called "string". Make the name describe the meaning.
这篇关于使用字符串传递文件名到fstream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!