从文件 c++ 读取并在需要时写入换行符

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

文件内容(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

我从文本文件中读取特定行的代码:

#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;
}

使用此代码时得到的输出:

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

想要的输出:

Line3
9
10
11
12

我想从文本文件中读取特定的一行并输出,如上所示。而且我还测试了 tahat 是否在 cpp 文件中有这样的字符串:

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

我得到了想要的输出。

请帮忙

当您阅读第三行时,它实际上包含“\n”序列。您需要用换行符替换它们。

#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;
}