我有一个包含 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++ 代码的结构或数据文件结构。如果无需额外的预处理指令就可以实现这一点,那将是更可取的。
非常感谢任何和所有的输入!
编辑:修复了类成员函数命名不一致和 sizeof() 使用不当的问题。我还在数据结构的名称字段中添加了一个可选字母,表明该名称可能包含空格,因此我不能单独依赖“>>”运算符,必须使用 getline。
最佳答案
流运算符使用空格。你只需要
void Letter::updateFromFile ( ifstream & file ) {
file.getline(name, STRLEN);
file >> num1 >> num2 >> ws; // eat the end of line
}
附加:
如果您可以控制该参数,我会将其更改为 istream &
,因为没有任何特定于文件流的操作。尽量使用能够正常工作的最不具体类型。
C 风格的数组比 std::array
和 std::vector
更古怪,更难安全使用,而且功能更差。今天使用它们的唯一原因是与 C 代码共享定义。
关于c++ - 具有挑战性的数据文件格式,需要读入包含类对象的数组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687519/