c++ - Reading from a file to a string doesn't work as expected -


i'm writing first programm in opengl , c/c++. came across following problem:

i wrote method reads file (in case containing vertex or fragment shader) , returns content 1 string.

std::string loadshader(const char* filepath) {     if(filepath){          std::ifstream ifs(filepath, std::ifstream::in);         std::ostringstream oss;         std::string temp;          while(ifs.good()){              getline(ifs, temp);             oss << temp << '\n';             std::cout << temp << std::endl;          }         ifs.close();         return oss.str();      }     else{        exit(exit_failure);     } } 

i've 2 files: vertexshader.glsl , fragmentshader.glsl want convert 2 seperate strings creation of shaders. code above called in following way:

void createshaders(void){      glenum errorcheckvalue = glgeterror();      const glchar* vertexshader = loadshader("vertexshader.glsl").c_str();     const glchar* fragmentshader = loadshader("fragmentshader.glsl").c_str();      vertexshaderid = glcreateshader(gl_vertex_shader);     glshadersource(vertexshaderid, 1, &vertexshader, null);     glcompileshader(vertexshaderid);      fragmentshaderid = glcreateshader(gl_fragment_shader);     glshadersource(fragmentshaderid, 1, &fragmentshader, null);     glcompileshader(fragmentshaderid);      // other code follows... } 

i debugged code above , noticed vertexshader const char* empty, while fragmentshader const char* contains correct code (the content file converted string).

i don't understand inconsistency in method. can't figure out, how 1 shader parsed right way , other empty.

i hope can figure out. thank much.

the problem unnamed std::string returned loadshader() exists within scope of expression:

const glchar* vertexshader = loadshader("vertexshader.glsl").c_str(); 

quoting standard:

temporary objects destroyed last step in evaluating full-expression (1.9) (lexically) contains point created.

the fix simple:

const std::string vertexshaderstr = loadshader("vertexshader.glsl"); const glchar *vertexshader = vertexshaderstr.c_str(); const std::string fragmentshaderstr = loadshader("fragmentshader.glsl"); const glchar *fragmentshader = fragmentshaderstr.c_str(); 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -