I also tried while(!inFile.eof()) and doing the infile>>'s inside the loop but then it reads through the list and every cout is the 1st line. I had this problem before which is why I switched to the current way of reading in. I'm stumped as to why this refuses to work. Any ideas?
counties is large enough to contain all the reads. counties is an array of county pointers with a max size of 3500 (there are only ~2100 lines in the usfips.txt). It fails before it even tries to call the constructor and initialize counties[i] so whatever it is, is in the file read, not the initialization.
I've provided the whole file this is countylist.cpp
#include <string>
#include <fstream>
#include <iostream>
#include "countylist.h"
#include "county.h"
usingnamespace std;
// Default constructor
countyList::countyList()
{
int i, stateId, countyId = 0;
string state, countyName;
// opens usfips file
ifstream inFile;
inFile.open("usfips.txt");
// checks to see if the file opened correctly
if (!inFile)
cout << "Error opening file\n";
else
{
// reads in and constructs all the county objects that are stored in counties[]
// reads in each element and seperates by comma stops when there is no more valid data to read
char comma[3];
cout << "file read\n";
while(inFile >> state >> comma[0] >> stateId >> comma[1] >> countyId >> comma[2] >> countyName && comma[0] == ',' && comma[1] == ',' && comma[2] == ',')
{
cout << i << " " << state << " "<< countyId << " " << stateId << " " << countyName << "\n";
counties[i] = new county(state, countyName, stateId, countyId);
i++;
}
// closes the file
inFile.close();
}
// returns the size of the good elements of the array
countiesSize = i;
}
// searches for and returns a the county instance that contains the info related to the state and fips code passed to it
county *countyList::findCounty(int state, int fips)
{
for (int i = 0; i <= countiesSize; i++)
{
cout << "loop " << i << endl;
// checks if countyList[i] has the correct state and fips id's
if (counties[i]->getStateId() == state && counties[i]->getCountyId() == fips);
return counties[i];
};
// upon failure return a blank county
county *ptr;
ptr = new county();
return ptr;
}
ok. I think I found the problem with the read. state is declared as a string and its reading in the whole line, ex. AL,01,001,Autauga then there is nothing to go into any of the other variables.
I found the crash too. it happens when I try to set countiesSize = to i. both are ints so I dont see why its causing a crash