简体   繁体   中英

C++ - Exception thrown: read access violation. Variable was nullptr

I have a program to read files from different locations from a folder. Once the file is successfully read, I assign the ifstream variable of the file to a temporary variable. Below code is an example:

while (!CBAsales.eof())
    {
        string sFilePath = "Datafolder/CBA/";
        sFilePath = sFilePath.append(sFileName);
        // Read the csv file
        infile.open(sFilePath);
        if (!infile)
        {
            cout << sFileName << ": File not found!!!" << endl;
            exit(1);
        }

        while (getline(infile, record, '\n'))
        {
            while (!infile.eof())
            {
                if (record.size() > 0)
                {
                    //insert elements here
                }
            }
        }
        infile.close();
        mapIAG.insert(pair<string, Vector<Stock>>(sFileName, V1));
        }

    CBAsales.clear();
    CBAsales.seekg(0, ios::beg);
    tempSales = &CBAsales;
}

This is the reading of the file. Now you can see tempSales = &CBAsales; where it is assigned to a temporary variable. I declared these variables globally and there is a pointer to tempSales shown below.

ifstream codeindex;
ifstream IAGsales;
ifstream CBAsales;
ifstream NABsales;
ifstream * tempSales;
ifstream infile;

Here is where I'm displaying all the necessary records:

cout << "Enter date of transaction" << endl;
while (!tempSales->eof())
{
    getline(*tempSales, record);
    cout << record << endl;
}

This is the error I get: http://i.imgur.com/I9lv2zv.png

Why is it pointing to null even though it was assigned? Am I using the pointer incorrectly?

your loop makes no sense. If we consider only the relevant variables it is equivalent to the code

while (!CBAsales.eof())
{
    CBAsales.clear();
    CBAsales.seekg(0, ios::beg);
    tempSales = &CBAsales;
}

Either the stream CBAsales is at the end of file in the first test, which means the code in the loop never execute or the loop execute forever.

If the loop never execute the statement tempSales = &CBAsales; is never executed and tempSales initial value is unchanged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM