Jason Lee
Jason Lee

Reputation: 41

Reading file into object array C++

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

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

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.

in the .h file

#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

in the implementation file

 #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

Upvotes: 3

Views: 5811

Answers (2)

AndersK
AndersK

Reputation: 36092

You should consider designing it a bit differently.

create a class that holds one line i.e. string int int int - like you have it in "Calc" but without making it dependent on how you create a line (readfile). Lets call it "Line"

class Line
{
public:
  std::string name;
  int a;
  int b;
  int c;  
};

Now since you need to read several lines you will need some kind of container to hold them, create a vector of Line (or some other container)

std::vector<Line> contents;

then override the stream operator as Tushar suggested so when you read from a file (or from e.g. stdin) you can create instances of Line for each line you read, these instances you use to fill the 'contents' array

now you can start doing whatever it is you want to do with the lines i.e. the actual operation calc

Upvotes: 0

Tushar
Tushar

Reputation: 8049

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;     
}

Now you can just do:

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

Upvotes: 2

Related Questions