Search code examples
c++printfifstreamstdstring

Why is NOT std::string defined in program equal to std::string loaded from file when printing out using prinft() and string::c_str()?


When i create std::string and define it in program like this and print it to console it looks like this:

std::string shader = "#version 330\nlayout(location = 0) in vec3 vp;void main(){gl_Position = vec4(vp, 1.0);}";
printf("Original: %s\n", shader.c_str());

Output: First output when defined in program and printed out

But when i load std::string from file the way below and then print it to console it looks like this:

std::string shader;
std::ifstream inputStream(path, std::ifstream::in);
if (inputStream.is_open())
{
    while (inputStream.good())
    {
        std::string line;
        getline(inputStream, line);
        shader.append(line);
    }
}
printf("LOADED: %s\n", shader.c_str());

Text file:

#version 330\n
layout(location=0) in vec3 vp;
void main ()
{
     gl_Position = vec4 (vp, 1.0);
}

Output: Second output when loaded from file and printed out

I need it do be same when loading from file. To be more specific i need it to use the special character \n.

When i try to remove '\n': pic3

The problem here is that i need new line between "..330" and "layout..."


Solution

  • Solution was to read text file by each character and then printing the string is correct.

    std::string shader;
    std::ifstream inputStream(path, std::ifstream::in);
    char character;
    if (inputStream.is_open())
    {
        while (inputStream.get(character))
        {
            shader += character;
        }
    }
    

    Output when printing shader:

    enter image description here

    Adding \n after each getline should work too.