【问题标题】:How to write a data to file each in separate line?如何将数据写入单独的行中的每个文件?
【发布时间】:2014-11-19 22:46:51
【问题描述】:

我想在单独的行中写入文件数据。代码如下:

#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,但它不起作用。你知道如何解决它吗?谢谢。

【问题讨论】:

  • 你在说什么?运行此文件后,它将创建一个新的,每个数字都在一个新行上。
  • 你使用什么编译器?我在visual studia 2013中运行它,它就像我说的那样工作......
  • 您正在将 ASCII 文本写入文件,那么为什么要使用二进制文件?
  • 好的,现在我知道我需要删除“std::ofstream::binary”。谢谢。
  • 我认为这实际上可能取决于您用来打开 newData.txt 的文本编辑器。

标签: c++ file io fstream


【解决方案1】:

不要将std::ofstream::binary 用于文本文件。打开方式:

ofstream outFile("newData.txt", std::ofstream::out);

或者等价的:

ofstream outfile("newData.txt");

【讨论】:

  • @user3603858 不使用?
  • 根据我的建议编辑。
【解决方案2】:

这是因为您以二进制模式打开文件。尝试 ofstream outFile("new.txt"),这将以文本模式打开文件,endl 现在应该在单独的行中写入数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多