流不追加换行符
stream does not append new line character
我在循环中调用函数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 或文件关闭)。尝试不同的编辑器以确保,但行尾应该是可见的。
珍
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 在 Stream C++ 文本之前有一个额外的换行符
- 流:CSV 文件中的换行符
- 如何在三元条件运算符中添加换行符和连接? :在 C++ 中
- Clang-格式:在多行语句之后的换行符上打开大括号
- 在输出流中插入换行符
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- QProcess::readAllStandardOutput() 和换行符
- 如果有换行符,clang 格式不会附加大括号
- 提取后返回换行符的C++istream.get()
- 如何在出现换行符之前将多个整数作为输入?
- 正则表达式 获取两个换行符之间的文本
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 在字符串中输入换行符
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- 使用 fgets() 从键盘读取时从以前的输入读取换行符
- C++ 换行符上的合并排序错误中断
- 在 std::string 的末尾插入换行符
- 流不追加换行符