DatabaseReader::DatabaseReader()
{
std::string completePath = "DB.txt";
std::ifstream DBFile;
DBFile.open(completePath);
if(!DBFile.is_open())
{
std::cout<<"Database file couldn't be opened :(\n"<<"Exiting......"<<std::endl;
sleep(5);
exit(1);
}
}
DatabaseReader::~DatabaseReader()
{
DBFile.close();
}
int DatabaseReader::getNumberofAvailableRecords()
{
std::string recordCount;
if(DBFile.good())
{
DBFile >> recordCount;
std::cout<<"Number of Records (if): "<<recordCount<<std::endl;
std::cout<<"DBFile : "<<(DBFile == 0)<<std::endl;
}
else
{
recordCount = "-1";
std::cout<<"Number of Records (else): "<<recordCount<<std::endl;
}
std::cout<<"Number of Records : "<<recordCount<<std::endl;
return std::stoi(recordCount);
}
When I run the program I get the following output:
1 2 3 4 5 6 7
Number of Records (if):
DBFile : 1
Number of Records :
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
This application has requested the Runtime to terminate it in an unusual way.
Since DBFile.good() was executed, I'd assume the file was opened. But (DBFile == 0) or (DBFile == NULL) prints 1.
Then when I attempt to check what was read from file into recordCount, "Number of Records :" prints out with no value. I'm expecting 2 since it's the first line in the file.
If your file exists then the file could be open, yet if the file is empty then the read of the recordCount could cause the stream to enter a failed state which will leave recordCount in it's default state (empty). Which is what appears to be happening since nothing is printed after the "(if): ".
Also look at the value of DBFile == 0 printout (1), which means that the stream is in a fail state.
By the way why is recordCount a string instead of some kind of number?
I moved std::ifstream DBFile; outside the constructor, before the constructor, and now it's working. But I'm a bit confused. Isn't all initialization supposed to be done inside of the constructor? Why didn't the original code work?