在C++中使用结构时出现输出问题
Output issues when working with structs in C++
我们刚刚开始在类中使用结构,并得到了预先存在的代码,并被告知接受结构的用户输入并创建一个打印清单的函数。这是我所做的:
#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。
相关文章:
- C++ 每次运行程序时我都会"nan"输出的问题
- 阶乘问题在 c++ 中给出错误的输出
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 代码输出随机符号,我不确定出了什么问题
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 向量<对<双精度,双精度>>给出问题
- 函数以相反的顺序输出输入问题,并改进算法以解释相等的数字
- 服务器未收到UDP数据包,花费数小时试图找出问题所在
- 子输出出现在主进程使用 system() 调用它之前
- Linux 标准输出管道问题
- C++中的代码输出出现问题
- c++输出格式问题
- fmod 输出有问题(长双精度、长双精度)
- C++ 输出找出问题
- c++中的输出文件问题
- 嵌套 std::map 的输出存在问题
- 在成功运行10小时后,在发布模式下从windows应用程序中获得异常,如何检测出问题
- 日志文件输出的问题-字符串和c_str之间的差异- c++
- 关于反汇编输出的问题
- c++输出的问题