我的许多程序都输出大量数据,供我在Excel上查看。查看所有这些文件的最佳方法是使用制表符分隔的文本格式。目前,我使用这段代码来完成它:

ofstream output (fileName.c_str());
for (int j = 0; j < dim; j++)
{
    for (int i = 0; i < dim; i++)
        output << arrayPointer[j * dim + i] << " ";
    output << endl;
}

这似乎是一个非常缓慢的操作,是将这样的文本文件输出到硬盘驱动器的更有效的方法吗?

更新:

考虑到这两个建议,新代码如下:
ofstream output (fileName.c_str());
for (int j = 0; j < dim; j++)
{
    for (int i = 0; i < dim; i++)
        output << arrayPointer[j * dim + i] << "\t";
    output << "\n";
}
output.close();

以500KB/s的速度写入高清

但这会以50MB/s的速度写入高清
{
    output.open(fileName.c_str(), std::ios::binary | std::ios::out);
    output.write(reinterpret_cast<char*>(arrayPointer), std::streamsize(dim * dim * sizeof(double)));
    output.close();
}

最佳答案

使用C IO,它比C++ IO快很多。我听说有人在编程竞赛中超时是因为他们使用C++ IO而不是C IO。

#include <cstdio>

FILE* fout = fopen(fileName.c_str(), "w");

for (int j = 0; j < dim; j++)
{
    for (int i = 0; i < dim; i++)
        fprintf(fout, "%d\t", arrayPointer[j * dim + i]);
    fprintf(fout, "\n");
}
fclose(fout);

只需将%d更改为正确的类型即可。

关于c++ - 创建制表符分隔的文本文件的更快方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2085639/

10-11 23:02
查看更多