using string to pass filename to fstream

2020-02-07 05:37发布

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?

3条回答
ら.Afraid
2楼-- · 2020-02-07 06:17

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.

查看更多
男人必须洒脱
3楼-- · 2020-02-07 06:19

Simply use c_str () method of std::string

modelStream.open(STRING.c_str (), ios::in);

查看更多
家丑人穷心不美
4楼-- · 2020-02-07 06:31

the standard streams doesn't accept a standard string, only c-string! So pass the string using c_str():

modelStream.open(STRING.c_str(), ios::in);
查看更多
登录 后发表回答