Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
374 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...