在C++中使用结构时出现输出问题

Output issues when working with structs in C++

本文关键字:输出 出问题 结构 C++      更新时间:2023-10-16

我们刚刚开始在类中使用结构,并得到了预先存在的代码,并被告知接受结构的用户输入并创建一个打印清单的函数。这是我所做的:

#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;
struct LineItem
{
    int quantity;
    string description;
    double price;
};
void print_inventory_report(LineItem[],const int);

int main()
{
  const int arraysize = 2;
  LineItem inventory[arraysize];
  for(int index = 0;index < arraysize;index++)
  {
      cout << "What part is this for (enter a one word description)? ";
      cin >> inventory[arraysize].description;
      cout << "Enter the quantity: ";
      cin >> inventory[arraysize].quantity;
      cout << "Enter the price: ";
      cin >> inventory[arraysize].price;
      cout << endl;
  }
  print_inventory_report(inventory,arraysize);
return 0;
}
void print_inventory_report(LineItem inv[], const int s)
{
    cout << "Totals: " << endl;;
    for(int i = 0; i < s;i++)
        cout << "  " << i+1 << ". " << inv[i].description << " $" << (inv[i].quantity * inv[i].price) <<endl;
        cout << endl;
}

基于此,如果用户输入以下内容:

What part is this for? (Enter a one word description) Struts
Enter the quantity: 2
Enter the price: 45.68
What part is this for? (Enter a one word description) Oil
Enter the quantity: 4
Enter the price: 5.74

我希望输出是:

Totals:
  1. Struts: $91.36
  2. Oil: $22.96

但相反,我得到这个:

Totals:
  1.   $7.95081e+070
  2.   $7.95081e+070

我还收到以下错误框:

错误信息

我遇到的两个问题是否相互关联?

我遇到的两个问题是否相互关联?

是的,因为您实际上是在访问您的程序不拥有的内存!因此,您输出垃圾值并收到相关的错误消息。在 Linux 中,我得到了:

gsamaras@gsamaras:~$ ./a.out 
What part is this for (enter a one word description)? Struts
Segmentation fault (core dumped)

您正在执行:

const int arraysize = 2;
LineItem inventory[arraysize];
...
cin >> inventory[arraysize].description;

所以现在你尝试越访问数组,因为索引开始了从 0.分段故障潜伏着。


您可以使用计数器执行以下操作:

cin >> inventory[index].description;

让自己为输入做好准备。更正代码中的所有相关错误后,您应该能够重新生成此行为:

gsamaras@gsamaras:~$ ./a.out 
What part is this for (enter a one word description)? Struts
Enter the quantity: 2
Enter the price: 3
What part is this for (enter a one word description)? Strats
Enter the quantity: 2
Enter the price: 3
Totals: 
  1. Struts $6
  2. Strats $6

你可能想看看我的例子mystruct。