Search code examples
c++newlinegetline

Getting '\n' from string


I have the text file called example.txt.

Its contents look something like this:

 Lorem ipsum dolor sit amet \n hey my name \n is

I open this file and grab all the lines with getline()

int main() {
    string s;
    ifstream test;
    test.open("example.txt");
    getline(test,s);
    cout<<s;
}

Now I want to see this

 Lorem ipsum dolor sit amet
 hey my name
 is 

But I see exactly what is in the text file.

Why does the \n symbol not move the cursor to the new line in this case?


Solution

  • Your text file contains separate \ and n characters. Unlike your C++ code, it's not pre-processed to turn those into newlines.

    You'll need to either write real newlines into your file, or to replace every "\\n" with "\n" in your string s after you've read it.