打开文件时出现C++错误
当我尝试打开文件以阅读我的控制台应用程序时,出现此错误消息:“Homework1.exe中0x1048766d(msvcp90d.dll)未处理异常:0xC0000005:访问冲突写入位置0x00000000。 “当我在我的MacBook上编译和运行该程序时它工作正常,但是当我使用VS 2008在我的桌面上运行它时,它给了我这个错误。打开文件时出现C++错误
这里是我的代码:
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
如果要检查,如果该文件是开放与否,不使用fin.bad()
代替:
while(!fin.is_open())
{
...
}
谢谢,阿拉克!您的解决方案奏效 – cskwrd 2009-09-13 17:47:57
确认您有权打开文件:既写并读取权限。
如何保证在阅读文件时库存中还有空位?库存是固定的大小,文件本质上不是......也许可能是,库存索引最终在数组本身之后指向,导致访问冲突?
由编译器和运行时选择是否以及如何在索引超出界限条件下做出反应。也许,在发布模式下进行编译时,甚至VS2008不会抱怨...
我应该澄清,我知道第一个文件将永远不会超过100个独特的产品 – cskwrd 2009-09-13 17:44:58
试着将使用VS2008时,部分代码会出现断点。
您可以按F10查看每行的行数并查看它崩溃的位置;这是你想要看的线。
代码标签似乎没有显示所有的代码,但它编译没有错误,所以我不知道发生了什么...... – cskwrd 2009-09-13 16:31:54
你能标记出引发异常的确切行吗? – mmmmmmmm 2009-09-13 16:32:45
'cout>文件名;' derobert 2009-09-13 16:36:15