We had a lab in my class today where we had to send file data (20 elements) into a class array (not an array of a class, but an array IN the class). The following is the way in which I did that:
#ifndef LABFOUR_H
#define LABFOUR_H
#include <iostream>
usingnamespace std;
//Class is defined
class SearchCount
{
private:
//Declares the number of elements for the class array
staticconstint SIZE=20;
int number[SIZE];
int counter;
public:
//Constructor
SearchCount()
{
//Initializes the array elements to 0
for(int i=0;i<SIZE;i++)
number[i]=0;
counter=0;
}
//Mutator Functions
void setNumber(int n)
{
number[counter]=n;
counter++;
}
void setCount(int co)
{ counter=co; }
//Accessor Functions
int getNumber(int c)
{ return number[c]; }
int getCount()
{ return counter; }
};
#endif
/*This program allows the user to search for a number using either linear
or binary means (Bubble and Selection sorting for binary)*/
#include <iostream>
#include <fstream>
#include "LabFour.h"
usingnamespace std;
//Simple functions to read file and display menu
void readFile(SearchCount[],int);
//**************************************************
//Main function
int main()
{
//Class object array is declared
constint NUM=3;
SearchCount order[NUM];
int option,
value,
//Holds values received from class functions
tempInt;
//Reads file
readFile(order,NUM);
return 0;
}
//**************************************************
/*Reads the file and saves the values equally among the
object array*/
void readFile(SearchCount order[], int NUM)
{
int tempInt;
ifstream readFile;
readFile.open("numbers.txt");
if(!readFile)
{
cout<<"Error opening file."<<endl;
cout<<"Press enter to exit the program."<<endl;
cin.get();
exit(0);
}
while(readFile>>tempInt)
{
//Assigns tempInt to every array element before reading the next number
//Loops depend on the size of the array
for(int i=0;i<NUM;i++)
{
order[i].setNumber(tempInt,i);
}
}
//Closes file
readFile.close();
}
Mind any things that seem out of place, I cut out what it is that I wanted to change so this is not the whole program.
The thing is, when I asked the professor about it he said it was fine. But when I asked him if I could have done it better, he said it would have been easier to just read and transfer the whole array from the main file. I am not sure what he meant by that and I didn't have time to ask him at the end of the class. Can anyone enlighten me on it, or perhaps suggest a better way of doing this? I know my own way is faulty because if they decided to initialize some numbers, it would get screwed.