如何将数据写入单独的行中每个文件
How to write a data to file each in separate line?
我想在单独的行中写入文件数据。代码如下所示:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void writeToFile(const vector<double> &data){
ofstream outFile("newData.txt", std::ofstream::binary);
double num1 = 1, num2 = 2, num3 = 4;
for (const auto &it : data) {
outFile << it << endl;
}
outFile.close();
}
int main(){
vector<double> data { 1, 2, 3, 4 };
writeToFile(data);
return 0;
}
"newData.txt"文件的输出为:
123
我想得到:
1
2
3
我使用 endl,但它不起作用。你知道怎么解决吗?谢谢。
不要对文本文件使用 std::ofstream::binary
。打开方式:
ofstream outFile("newData.txt", std::ofstream::out);
或等效地只是:
ofstream outfile("newData.txt");
这是因为您正在以二进制模式打开文件。尝试 ofstream outFile("new.txt"),这将以文本模式打开文件,endl 现在应该在单独的行中写入数字。
相关文章:
- 用C++在单独的头文件中完成函数体
- 如何使用单独文件中的派生类访问友元函数对象
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 如何将 2 个类分成单独的 .h 文件并正确设置它们
- C++ 链接到单独的.cpp文件说"multiple definitions"
- 从单独的文件中读取树
- 当结构位于单独的头文件中时'unregistered datatype'在 QML 中出现Q_GADGET错误
- 使用 Premake5 构建库,每个构建没有单独的项目文件
- 为什么要将函数声明和定义放在单独的文件中
- 使用 #include 将大量重复代码放入单独的文件中是否可以和/或正常?
- 创建单独的实现文件和头文件
- 在C++中对文件中的值单独执行计算
- 使用 ctest 的每个测试都需要单独的文件吗?
- 好友成员函数可以在单独的文件中使用吗?
- 运行单独的 cpp 文件,每个文件都有 main()
- 在 h 和 cpp 文件中单独声明和实现模板有时有效,有时会出现链接器错误
- 单独的类声明和方法定义文件问题
- 如何在C 中的Little Endian中读取来自二进制文件的单独的十六进制字符
- Howo 使用 cl 预处理为 masm 组装生成一个单独的文件
- 单独文件中各种 c++ 类的标头出现问题