具有挑战性的数据文件格式,需要读入包含 class 个对象的数组变量

Challenging data file format which needs to be read into vars of array containing class objects

我有一个包含 class 垃圾的 5 个实例的程序,垃圾有 3 个变量,我需要从数据文件更新。第一个是 char 数组,其他两个整数。除了更新 int 变量之外的所有工作,我不知道如何实现它,所以非常感谢任何帮助。我的代码:

#include <iostream>
#include <cctype>
#include <cstring>
#include <fstream>
#include <iomanip>

using namespace std;

class Garbage {
  public:
    void writeData();
    void updateFromFile( ifstream & file );
  private:
    char name[40];
    int num1;
    int num2;
};

void Garbage::writeData() { 
  cout << name << ", " << num1 << ", " << num2 << endl;
}

void Garbage::updateFromFile ( ifstream & file ) {

  if ( !file.eof() ) {

    file.getline(name, STRLEN);

    /*
    Int variables from Garbage class need to be updated here
    */

  }

}

void readFile() {

  ifstream infile("data.txt");

  for(int i = 0; i < sizeof(garbages)/sizeof(garbages[0]); i++) {
    garbages[i].updateFromFile(infile);
  }

}

Garbage garbages[5];

int main() {
  readFile();

  for(int i = 0; i < sizeof(garbages)/sizeof(garbages[0]; i++) {
    garbages[i].writeData();
  }

  return 0;
}

"data.txt"的数据结构如下:

lorem A
10 20
ipsum B
20 30
dolor C
30 40
sit D
40 50
amet E
50 60

lorem 是字符数组(可能包含空格!),10 是 num1,20 是 num2 等等。由于这是一项学校作业,我无法更改 C++ 代码的结构或数据文件结构。如果没有额外的预处理指令就可以实现这一点,那将是更可取的。

非常感谢任何和所有输入!

编辑: 修复了 class 成员函数命名不一致和 sizeof() 使用不当的问题。我还在数据结构的名称字段中添加了一个可选字母,表明该名称可能包含空格,因此我不能单独依赖“>>”运算符,必​​须使用 getline。

流运算符消耗空白。您只需要

void Letter::updateFromFile ( ifstream & file ) {
  file.getline(name, STRLEN);
  file >> num1 >> num2 >> ws; // eat the end of line
}

补充: 如果您可以控制该参数,我会将其更改为 istream &,因为没有任何特定于文件流的内容。努力使用能够正常工作的最不具体 类型。

C 风格的数组比 std::arraystd::vector 更古怪,更难安全使用,而且功能更少。 唯一 今天使用它们的原因是为了与 C 代码共享定义。