读文件到对象数组C ++ [英] Reading file into object array C++

查看:81
本文介绍了读文件到对象数组C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从被格式化像这样的数据文件中读取

I have to read from a data file which is formatted like this

ABCD(字符串)1(INT)2(INT)3(INT)搜索
ABCDE(串)4(INT)3(INT)2(int)的结果,
。结果
。结果

abcd(string) 1(int) 2(int) 3(int)
abcde(string) 4(int) 3(int) 2(int)
.
.
.

欲执行哪种使用中的变量仅在同一行的一些功能。但这里是我的code。我是个初学者,所以请指正谢谢。

I want to perform some functions which use the variables in the same line only. But here's my code. I'm a beginner so please correct me thank you.

在.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();

然后我想显示什么,我只是从文件中读取

and then I want to display what i just read from the file

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

对不起,我离开了很多东西我只是想知道如果我在正确的道路上。谢谢

sorry I left out alot of stuff I just want to know if I on the right path. Thanks

推荐答案

要做到这一点,正确的方法是超载&GT;&GT; 运营商类计算器

The proper way to do this is to overload the >> operator for your class 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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆