【问题标题】:How to write the content of an array into a text file?如何将数组的内容写入文本文件?
【发布时间】:2014-04-07 01:20:53
【问题描述】:

如何将数组的内容写入文本文件? 有可能吗?

下面是我的代码:

x=0;
y=0;
//copy to real array
if(nRow == 0){
    for(i=nTCol; i>=0 ; i--){
        nPanelMap[nRow][x] = nTempMap[i];
        x++;
    }

}
if(nRow == 1){
    for (i=nTCol; i>=0 ; i--){
        nPanelMap[nRow][y] = nTempMap[i];
        y++;
    }
}
k=0;

for (i=nTCol; i>=0 ; i--){
    array [k] = nPanelMap[nRow][x];
    k++;
    array [k] = nPanelMap[nRow][y];
    k++;

}
j=0;
for (i=nTCol; i>=0 ; i--){

    nPanelMap[nRow][j] = array [k];
    j++;
}
nRow++;

我想打印出数组xykj 并将它们写入文本文件。 这样做的目的是为了保证数据传递是正确的。

【问题讨论】:

  • 对于写入文本文件来说,here 是一个很好的关于 C++ 的教程/概要.

标签: c++ arrays logging


【解决方案1】:

是的,您可以写入文本文件。

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  const int size = 5;
  double x[] = {1,2,3,4,5}; 

  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    for(int count = 0; count < size; count ++){
        myfile << x[count] << " " ;
    }
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}

更多参考: http://www.cplusplus.com/doc/tutorial/files/

要写入数组数据,请使用这个。

for(int count = 0; count < size; count ++){
            out_myfile << x[count] << " " ;
}

【讨论】:

  • 如何将数组的内容写入文本文件?
  • 所以,你永远不会定义out_myfile。我猜这应该是myfile?另外,a 应该是 count 吗?
  • @dbliss 可以定义它,但 x 用于假设数组。
  • 写入缓冲了吗?还是一个字节一个字节地写?
【解决方案2】:

我的建议是,如果您希望生成的文件具有人类可读性,请使用 JSON(JavaScript 对象表示法)格式。 JSON 记录在 http://json.org/。在https://github.com/Loki-Astari/ThorsSerializer 找到的 ThorsSerializer 是 JSON 的 C++ 序列化库。序列化,如http://en.wikipedia.org/wiki/Serialization 所定义,“是将数据结构或对象状态转换为可以存储(例如,在文件或内存缓冲区中,或通过网络连接链路传输)并在以后重建的格式的过程。相同或其他计算机环境。”如果 ThorsSerializer 对您不起作用,我建议您在 Google 上搜索“C++ JSON 序列化库”。

我在 Google 搜索时发现的另一个选项是“谷物 - 用于序列化的 C++11 库”,位于 http://uscilab.github.io/cereal/

【讨论】:

  • 在应用程序中保存和加载数组时应考虑使用 JSON,但恕我直言,为了调试目的而转储数组是一种过度杀伤力。
【解决方案3】:

使用 fstream 类进行文件写入、读取、追加、查找等操作。

【讨论】:

    猜你喜欢
    • 2012-10-12
    • 2013-01-02
    • 2021-03-11
    • 2022-01-09
    • 1970-01-01
    • 2020-06-30
    • 2011-03-05
    • 2014-02-17
    • 2014-02-28
    相关资源
    最近更新 更多