I’m working on a program which reads some data from a file formatted like so:
21
285 270 272 126 160 103 1
31
198 180 163 89 94 47 1
32
240 230 208 179 163 104 1
33
15 13 12 14 15 15 0
34
63 61 62 24 23 20 2
I’m trying to read the first number into one pointer array and the other 7 numbers into a parallel two dimensional pointer array but for some reason, every time I run my code it just stops working. It’s not returning an error but I feel like my pointer usage is wrong because this is my first time using pointers. The data file is called “election_data_121.txt”, fyi. Heres the code. If anyone could take a look I’d be so grateful:
#include <iostream>
#include <fstream>
using namespace std;
//bool openFileIn(fstream &, char *);
int main()
{
const int PREC_SIZE = 30;
const int CANIDATES = 7;
int *precinct_num[PREC_SIZE];
int *num_votes[PREC_SIZE][CANIDATES];
cout << "Declarations made." << endl;
fstream dataFile; //Make a file handle
cout << "File object made." << endl;
//Open the file and check that it opened correctly
if(!openFileIn(dataFile, "election_data_121.txt"))
{
cout << "File open error!" << endl;
return 0; //Exit the program
}
cout << "File opened." << endl;
//Read the contents of the file into the proper arrays
int counter = 0;
while(!dataFile.eof())
{
dataFile >> *precinct_num[counter];
for(int i = 0; i < 7; i++)
{
dataFile >> *num_votes[counter][i];
}
counter++;
}
//Print out the data
for(int j = 0; j < counter; j++)
{
cout << *precinct_num[j];
for(int i = 0; i < 7; i++)
{
cout << *num_votes[j][i];
}
}
dataFile.close();
cout << "End of file";
return 0;
}
bool openFileIn(fstream &file, char *name)
{
file.open(name, ios::in);
if(file.fail())
return false;
else
return true;
}
Thanks again!
This code doesn’t need pointers at all; why would you think it does? Just change the types of
precinct_numandnum_votesand stop dereferencing them and I think (at a glance) that it should be fine.