[英]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. 成功读取文件后,我将文件的ifstream变量分配给一个临时变量。 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; 现在您可以看到tempSales =&CBAsales; where it is assigned to a temporary variable. 分配给临时变量的位置。 I declared these variables globally and there is a pointer to tempSales shown below. 我在全局上声明了这些变量,并且有一个指向tempSales的指针,如下所示。
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 这是我得到的错误: http : //i.imgur.com/I9lv2zv.png
Why is it pointing to null even though it was assigned? 为什么即使分配了它也指向null? 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. 在第一次测试中,流CBAsales
位于文件末尾,这意味着循环中的代码永远不会执行,或者循环永远执行。
If the loop never execute the statement tempSales = &CBAsales;
如果循环从不执行语句tempSales = &CBAsales;
is never executed and tempSales
initial value is unchanged. 永远不会执行,并且tempSales
初始值不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.