gpt4 book ai didi

c++ - 使用 std::ostream 在每一行之前插入文本

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:17 24 4
gpt4 key购买 nike

我想知道是否可以从 std::ostream 继承,并以在每行的开头添加一些信息(比如行号)的方式覆盖 flush()。然后我想通过 rdbuf() 将它附加到 std::ofstream (或 cout),以便我得到这样的东西:

ofstream fout("file.txt");
myostream os;
os.rdbuf(fout.rdbuf());

os << "this is the first line.\n";
os << "this is the second line.\n";

将其放入 file.txt

1 this is the first line.
2 this is the second line.

最佳答案

flush() 不会是在此上下文中要覆盖的函数,尽管您走在正确的轨道上。您应该在底层 std::streambuf 接口(interface)上重新定义 overflow()。例如:

class linebuf : public std::streambuf
{
public:
linebuf() : m_sbuf() { m_sbuf.open("file.txt", std::ios_base::out); }

int_type overflow(int_type c) override
{
char_type ch = traits_type::to_char_type(c);
if (c != traits_type::eof() && new_line)
{
std::ostream os(&m_sbuf);
os << line_number++ << " ";
}

new_line = (ch == '\n');
return m_sbuf.sputc(ch);
}

int sync() override { return m_sbuf.pubsync() ? 0 : -1; }
private:
std::filebuf m_sbuf;
bool new_line = true;
int line_number = 1;
};

现在您可以:

linebuf buf;
std::ostream os(&buf);

os << "this is the first line.\n"; // "1 this is the first line."
os << "this is the second line.\n"; // "2 this is the second line."

Live example

关于c++ - 使用 std::ostream 在每一行之前插入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23688447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com