当我尝试在我的控制台应用程序中打开一个文件进行读取时,我收到此错误消息:“homework1.exe中0x1048766d(msvcp90d.dll)的未处理异常:0xC0000005:访问冲突写入位置0x00000000 . ”当我在我的macbook上编译和运行程序时它工作正常但是当我使用VS 2008在我的桌面上运行它时它给了我这个错误 .
这是我的代码:
int main (void){
//Open 1st file (baseproduct.dat)
ifstream fin;
//fin.open(filename.c_str());
fin.open("baseproduct.dat");
int tries;
tries = 0;
while( fin.bad() )
{
if( tries >= 4 )
{
cout > filename;
fin.open(filename.c_str());
tries++;
}
SodaPop inventory[100];
//read file into array
string strName;
double dblPrice;
int i;
i = 0;
fin >> strName;
while( !fin.eof() )
{
inventory[i].setName(strName);
fin >> dblPrice;
inventory[i].setPrice(dblPrice);
fin >> strName;
i++;
}
fin.close();
cout > filename;
//fin.open(filename.c_str());
fin.open("soldproduct.dat");
tries = 0;
while( fin.bad() )
{
if( tries >= 4 )
{
cout > filename;
fin.open(filename.c_str());
tries++;
}
//read file into array
i = 0;
fin >> strName;
while( !fin.eof() )
{
cout > dblPrice;
inventory[i].setPrice(dblPrice);*/
fin >> strName;
i++;
//1. search array for name
//2. get price (what should happen with it?)
//3. add # sold to quantity
}
fin.close();
cout
5 回答
您如何保证在阅读文件时库存中仍有位置?库存是固定大小的,文件本身就不是......可能是库存索引最终指向数组本身后导致访问冲突?
由编译器和运行时决定是否以及如何对索引超出边界条件做出反应 . 也许,在发布模式下编译时,即使VS2008也不会抱怨......
使用VS2008时,请尝试在代码的某些部分放置断点 .
您可以按F10查看每行的行数,并查看它崩溃的位置;这就是你想看的那条线 .
验证您是否有权打开该文件:写入和读取权限 .
如果要检查文件是否打开,请不要使用
fin.bad()
:尝试在打开时为通话添加“模式”,如:
http://www.cplusplus.com/reference/iostream/ifstream/open/