首页 文章

0xC0000005:访问冲突读取位置0xCCCCCCCC [关闭]

提问于
浏览
-2

现在,我一直在为我的实验室编写这个代码,我只是想编写一段创建二进制.dat文件的代码,将二进制数据写入其中,然后输出信息 . 我一直遇到的问题是,在帮助将数据写入文件的代码行上,我总是抛出这个异常,读取“0xC0000005:访问冲突读取位置0xCCCCCCCC” .

此外,我用来显示信息的for循环坚持我用来控制循环的整数,以及我输出信息的一行需要指针到对象类型 .

我不知道Visual Studio想要什么,所有的帮助表示赞赏 .

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

struct Inventory
{
    char desc[30];
    int qty;
    double wholeSaleCost;
};

//prototypes
//void addRecord(fstream &);
void viewRecord(fstream &);
//void changeRecord(fstream &);
//void testRecord(fstream &);

int main()
{
    fstream inventoryFile;
    int choice;
    cout << setprecision(2) << fixed;

    do
    {
        //Display menu
        cout << "\n1.  Add a new record\n";
        cout << "2.  View an existing record by record number\n";
        cout << "3.  Change an exisiting record\n";
        cout << "4.  Exit\n\n";
        do
        {
            cout << "Enter your choice (1-4): ";
            cin >> choice;
        } while (choice < 1 || choice > 4);

        switch (choice)
        {
            //Add record
            case 1:
                //      addRecord(inventoryFile);
                break;

                //View record
            case 2:
                viewRecord(inventoryFile);
                break;

                //Change record
            case 3:
                //      changeRecord(inventoryFile);
                break;

            case 4:
                break;

            default:
                break;
        }
    } while (choice != 4);

    cout << "\nThank you for visiting my store." << endl;

    system("pause");
    return 0;
}

void viewRecord(fstream &inventoryFile)
{
    Inventory stuff;
    inventoryFile.open("C:\\Windows\\Temp\\inventoryFile.dat", ios::out |
                               ios::binary);

//Write data into the file
    inventoryFile.write(reinterpret_cast<char *>(stuff.desc),
                        sizeof(stuff.desc));
    inventoryFile.write(reinterpret_cast<char *>(stuff.qty), sizeof(stuff.qty));
    inventoryFile << setprecision(2) << stuff.wholeSaleCost;

    inventoryFile.close();
    inventoryFile.open("inventoryFile.dat", ios::in | ios::binary);

//Read data from the file
    inventoryFile.read(reinterpret_cast<char *>(stuff.desc),
                       sizeof(stuff.desc));
    inventoryFile.read(reinterpret_cast<char *>(stuff.qty), sizeof(stuff.qty));
    inventoryFile << setprecision(2) << stuff.wholeSaleCost;

    for (int i = 0; i < 5; i++)
    {
        cout << setprecision(2);
        cout << "Product: " << stuff.desc[i] << endl;
        cout << "Quantity: " << stuff.qty[i] << endl;
        cout << "Retail price: " << stuff.wholeSaleCost[i] << endl;
    }
    cout << endl;

    inventoryFile.close();
}

1 回答

  • 1

    您正在尝试在类型double上使用[]运算符并键入结构的int成员 .

相关问题