【问题标题】:C++ File Output for object arrays对象数组的 C++ 文件输出
【发布时间】:2019-12-04 05:12:57
【问题描述】:

有谁知道如何将像下面这样的数组写入 .dat 文件? 如果这还不够信息,请告诉我。

我的控制台输出显示 4 行 6 列的整数,我想将其打印到我的文件中。我可以打印其他所有内容,但无法弄清楚这一点..

for(i=0; i < 4; i++)
{ 
    cout << "  " << i+1; 
    P[i].TeamOutput();
}     

void TeamOutput()           
{
    cout << teamwork << speed << power << defence << injury << endl;    
}

【问题讨论】:

  • 您使用什么格式的输出文件:二进制(内存中的镜像)、xml、ini、CSV 等?在某些情况下,您需要人类可读且易于编辑的格式;在其他情况下,您可能想要一些可以有效阅读的内容(并且在很大程度上是特定于平台的)。
  • 顺便说一句,“.dat”文件没有标准格式。 “.dat”扩展名意味着文件包含数据;通常采用程序特定的格式。需要更多详细信息。
  • 在发布的代码中哪里打印了 6 列?我所看到的只是一个方法,TeamOutput 被调用了 4 次。
  • 您可能需要考虑将输出流(通过引用)传递给您的类的输出方法。这将为您提供更多选择,例如文件流和字符串流。
  • Windows 记事本是一个编辑器。你可以写FORTRAN、COBOL。 LISP、BASIC、C、C++、C#、Pascal、Algol、Ada、Haskell、Smalltalk 等,使用记事本。您需要弄清楚您使用的是哪种编程语言。

标签: c++ arrays class object


【解决方案1】:

你几乎拥有它。您需要一个特定类型的ostream 来输出。 cout 是一个ostream,但它是一个特殊的输出到系统控制台的。您需要一个输出到文件的ostream。这种ostream 称为ofstream,在头文件&lt;fstream&gt; 中。以下是如何将它与数组一起使用。

#include <iostream>
#include <fstream>
using namespace std; // It's generally bad to do this

int main()
{
    // Size of array
    const int SIZE = 10;

    // Make the array
    int some_array[10];

    // Fill the array with values
    for (int i = 0; i < SIZE; i++)
    {
        some_array[i] = i + 1;
    }

    // THIS is where the magic happens; make the file stream to output to
    ofstream file("file.dat"); // "file.dat" can be replaced by whatever filename

    // Make sure the file opened okay. Otherwise, there's an error
    if (file.is_open())
    { // The file opened just file, so do whatever you need to

        // Save all the info from the array to "file.dat"
        for (int i = 0; i < SIZE; i++)
        {
            file << some_array[i] << endl;
        }

        // Make sure to close the 'ofstream' when you're done
        file.close();
    }
    else
    { // The file did NOT open okay; there's an error
        cout << "Error opening file.dat!" << endl;
    }
}

【讨论】:

  • 这是输出一个正则数组。我需要输出一个填充成员函数的数组。我最初的反应是尝试以下方法,但它不起作用:file
猜你喜欢
  • 2017-09-08
  • 1970-01-01
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 2019-03-30
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多