尝试打印数组元素返回“访问冲突读取位置0xCCCCCCCC。发生”

问题描述 投票:0回答:1

此代码用于一个项目,当给出这样的文本文件时:

14.99 24 Hat
29.99 31 Shirt
17.99 12 Shorts
5.50 18 Socks
-1 -1 endofdata

应该打印出某种“收据”,但是当我尝试打印array [i] .name时,我在第73行遇到了一个异常(在此输入大写字母注释)。我试图将其更改为&array [i] .name(以及我尝试打印的其他元素),并且它可以很好地打印地址。我将衷心感谢您的帮助。代码显示在下面。

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

struct prod {
    string name;
    float price;
    int inStock;
};

void swapName(string* name1, string* name2) {
    string temp = *name1;
    *name1 = *name2;
    *name2 = temp;
}

prod readInventory(prod array[], int max) {
    ifstream inventoryF("inventory.txt");
    if (inventoryF.fail()) {
        cout << "Unable to open input file.\n";
        for (int i = 0; i < 3; i++) {
            array[i].price = 0;
            array[i].inStock = 0;
            array[i].name = " ";
        }
    }
    else {
        int i = 0;
        while (array[i].price > 0) {

            inventoryF>> array[i].price;
            inventoryF >> array[i].inStock;
            inventoryF >>array[i].name;
            i += 1;
        } 
        cout << "Inventory read."<< endl;
    }
    return *array;
}

float totalValue(prod array[]) {
    int i = 0;
    float total = 0;
    while (array[i].price> 0) {
        total+=array[i].price* array[i].inStock;
        i++;
    }
    return total;
}

prod sortByName(prod array[]) {
    for (int i = 0; i < 5; i++) {
        if (array[i].name > array[i + 1].name) {
            swapName(&array[i].name, &array[i + 1].name);
        }
    }
    cout << "Poducts sorted by name.\n";
    return *array;
}

void writeReport(prod array[],int max) {
    cout <<setprecision(2)<< "+---------------------------+" << endl;
    cout << "|     Current Inventory     |" << endl;
    cout << "+---------------------------+" << endl;
    cout << left << setw(15) << "NAME" << setw(12) << "PRICE" << "#" << endl;
    cout << "------------  -------     ---" << endl;
    int j = 0;
    float total = totalValue(array);
    for (int i =0;i< max;i++){
        //PROBLEM IS ON THE LINE BELOW
        cout << left << setw(15) << array[i].name << setw(2) << "$" << array[i].price<< right << array[i].inStock<< endl;
        j++;
    }
    cout << "+---------------------------+" << endl;
    cout << left << setw(22) << "Number of products:" << j << endl;
    cout << setw(22) << "Inventory total value:" << total << endl;;
}


int main() {
    const int prodMax = 20;
    int current = 0;
    prod productArray[prodMax];
    prod temp = readInventory(productArray, prodMax);
    //temp = sortByName(&temp);
    writeReport(&temp, prodMax);
    system("pause");
    return 0;
}
c++ arrays exception memory-management
1个回答
0
投票

我很确定如果不包含<string>,您将无法打印字符串。

© www.soinside.com 2019 - 2024. All rights reserved.