gpt4 book ai didi

c++ - 尝试打印数组元素返回 “Access violation reading location 0xCCCCCCCC. occurred”

转载 作者:行者123 更新时间:2023-12-01 14:53:07 25 4
gpt4 key购买 nike

这段代码是针对一个项目的,当给定这样的文本文件时:

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;
}

最佳答案

您的readInventory()函数固有存在缺陷。您将返回一系列产品的初始产品。如果要返回整个数组,则需要使readInventory返回prod *,然后从return *array更改为return array。意思是,通过将&temp传递给writeReport(),您传递的是1个产品的数组,这当然会导致读取访问冲突。

关于c++ - 尝试打印数组元素返回 “Access violation reading location 0xCCCCCCCC. occurred”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61002351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com