Search code examples
c++stringreadfileifstream

Read from file c++ and write new line character when needed


Content of the file (test_file.txt):

Line1\n 1\n 2\n 3\n 4\n
Line2\n 5\n 6\n 7\n 8\n
Line3\n 9\n 10\n 11\n 12\n
Line4\n bla\n bla\n bla\n bla\n
Line5\n etc\n etc\n etc\n etc\n

My code for reading a specific line from the text file:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream f("test_file.txt");
    string s;

    for (int i = 1; i <= 3; i++)
        getline(f, s);

    cout << s;
    return 0;
}

Output I get when using this code:

Line3\n 9\n 10\n 11\n 12\n

Wanted output:

Line3
9
10
11
12

I want to read one specific line from text file and output it as shown above. And I also have tested tahat if have that string in cpp file like this:

string s;
s = "Line3\n 9\n 10\n 11\n 12\n";
cout << s;

I get the wanted output.

Please help.


Solution

  • When you read your third line it will actually contain '\n' sequences. You'll need to replace them with new line characters.

    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    std::string& fix_newlines(std::string& s)
    {
        size_t start_pos = 0;
        while((start_pos = s.find("\\n", start_pos)) != std::string::npos) {
             s.replace(start_pos, 2, "\n");
             start_pos += 1;
        }
        return s;
    }
    
    int main()
    {
        ifstream f("test_file.txt");
        string s;
    
        for (int i = 1; i <= 3; i++)
            getline(f, s);
        fix_newlines(s);
        cout << s;
        return 0;
    }