gpt4 book ai didi

c++ - 将文件读入对象数组C++

转载 作者:太空狗 更新时间:2023-10-29 21:46:19 25 4
gpt4 key购买 nike

我必须从这样格式的数据文件中读取

abcd(字符串) 1(整数) 2(整数) 3(整数)
abcde(字符串) 4(整数) 3(整数) 2(整数)
.
.
.

我想执行一些仅使用同一行中的变量的函数。但这是我的代码。我是初学者,请指正谢谢。

在.h文件中

#include <string>
using namespace std;


#ifndef CALC_H
#define CALC_H


class Calc
{
public:

void readFile(string file);

private:

string name;
int a;
int b;
int c;
};

#endif

在实现文件中

 #include "Vehicle.h"  
#include iostream>
#include fstream>
#include string>
#include cstdlib>
#include cmath>

using namespace std;


void Vehicle::readFile(string filename)
{
ifstream myIn;

int totalNum=0;

myIn.open(filename.c_str());
if (!myIn)
{
cerr<<"Data file failed to open!\n";
exit (0);
}
for (int i=0; i<MAX; i++)
{
while (myIn.peek() != EOF)
{
myIn>>calc[i].name;
myIn>>calc[i].a;
myIn>>calc[i].b;
myIn>>calc[i].c;

totalNum++;
}
}
myIN.close();

然后我想显示我刚刚从文件中读取的内容

 for (int i = 0; i < MAX; i++)  
cout << calc[i].name << calc[i].a << calc[i].b << calc[i].c << endl;

抱歉,我遗漏了很多东西,我只是想知道我是否走在正确的道路上。谢谢

最佳答案

执行此操作的正确方法是为您的类 Calc 重载 >> 运算符。

class Calc {
public:
friend istream& operator >>(istream& myIn, Calc& calc);
};

istream& operator >>(istream& myIn, Calc& calc) {
myIn >> calc.name;
myIn >> calc.a;
myIn >> calc.b;
myIn >> calc.c;

return myIn;
}

现在你可以这样做:

while (myIn >> calc[i]) {
++totalNum;
}

关于c++ - 将文件读入对象数组C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com