samedi 31 juillet 2021

Problem with C++ class instance not being recognized

This is for "homework" but this is not an algorithm question, but rather a programming issue. As part of a project for my Data Structures class, I have to write a class to act as a database. That part is done. I am not asking about the algorithm, but rather, trying to isolate what is clearly a stupid bug on my part.

PeopleDB has two constructors, the default one and one that takes as a parameter an input file and reads it into the database to initialize it.

Here is the code snippet, the problem is described below it:

#include "People.h" // People class definition
#include "PeopleDB.h" // People database class
#include "PrecondViolatedExcep.h"

using namespace std;

int main(int argc, char *argv[])
{
    // Define variables
    string infilename;
    PeopleDB mydb;

    // Get the filename of the text file to process
    infilename = argv[1];

    // Try to open import the data into a database instance
    try
    {
        cout << "Attempting to import DB entries from "<< infilename << endl;
        PeopleDB mydb(infilename);
        cout << "# A total of "<< mydb.countEntries() << " DB entries loaded." << endl;
    }
    catch(PrecondViolatedExcep e)
    {
        cout << e.what() << endl;
        cout << "Exiting program.";
        exit(1);
    }

    // Display database contents
    cout << endl;
    cout << "# A total of "<< mydb.countEntries() << " DB entries found before display." << endl;

    return 0;
}  // end main

The problem is if I don't include the PeopleDB mydb; constructor at the top of the main() loop, the compiler barfs saying it doesn't recognize the mydb.countEntries() in the second to last line of the main loop. But if I do include it, it is clear that the mydb within the try loop doesn't survive because the output of the program is:

Attempting to import DB entries from testinput.txt
# A total of 7 DB entries loaded.

# A total of 0 DB entries loaded.

I didn't want to use the same variable (mydb) twice (I actually assumed this would error out during compiling), but for some reason creating the mydb instance of PeopleDB inside the try block doesn't seem to survive to be outside the block. I am sure this is something stupid on my part, but I am not seeing it. It has been a long day, so any suggestions would be appreciated.

Aucun commentaire:

Enregistrer un commentaire