流不追加换行符

stream does not append new line character

本文关键字:换行符 追加      更新时间:2023-10-16

我在循环中调用函数write。我需要附加几行。

我通过

std::fstream file(filename);

write(info, &file);

以下代码不追加换行符,或者至少 Notepad++ 不显示它。(我只得到一个空格):

void IO::write(const std::string& name, std::iostream* stream)
{
    (*stream) << "usr" << name << " === " << "n";
}

怎么了?如何将新行附加到文本文件?

详细说明我相当严厉的评论,您的换行符没有错,但是......

。使用正确的类型...

#include <iostream>
#include <fstream>
// ...
std::ofstream file( filename );
// ...

。如果您想将info打印到流中,只需这样做而不是通过某些功能...

// ...
file << "usr" << info << " === " << "n";
// ...

。如果你真的让它成为一个函数,至少使用引用和正确的类型......

void IO::write( std::ostream & stream, const std::string & name )
{
    stream << "usr" << name << " === n";
}
// ...
IO::write( file, info );
// ...

。但是在 C++ 中执行输出的"传统"方法是重载相关类的operator<<,并让打印实例的实现与类成员实现并排,而不是通过 C 样式函数......

class MyClass
{
    // ...
    friend std::ostream & operator<<( std::ostream & stream, const MyClass & obj );
    // ...
};
std::ostream & operator<<( std::ostream & stream, const MyClass & obj )
{
    stream << "usr" << obj.name << " ===n";
    return stream;
}
// ...
MyClass mine;
file << "Hellon" << mine << 42 << "n";
我还建议您使用 std::endl 而不是 "

"。 std::endl 刷新文件,""不会。

刷新文件后(使用标准::endl 或文件关闭)。尝试不同的编辑器以确保,但行尾应该是可见的。