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 functionstd::string::c_str()
: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.
Simply use
c_str ()
method ofstd::string
modelStream.open(STRING.c_str (), ios::in);
the standard streams doesn't accept a standard string, only c-string! So pass the string using c_str():