我搜索了互联网的各个角落来寻找这个问题的答案。“做编程练习4,但
使用 new 来分配结构体而不是声明结构体变量。 此外,让程序在请求披萨公司名称之前请求披萨直径。”
我辅修计算机科学,但自从我做任何编程以来已经有一段时间了,我想对自己进行测试,加强我所知道的,看看我是否可以自己学习更多。无论如何,我遇到了这个问题,却找不到一个好的例子来模仿,所以在多次尝试后,我终于明白了,我想与任何将来可能会遇到这个问题的人分享我的代码,或者以便我将来需要时可以找到它。我使用了 MS visual studios,所以请根据您的编译器进行调整。
对于第一个问题,始终回答 3 或修改代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include "stdafx.h" //you may have to remove this depending on you compiler
#include <iostream>
using namespace std;
struct Pizza_Analysis //defining the struct
{
char company_name[35];
double dia_of_pizza;
double weight_of_pizza;
};
int main()
{
int num_of_companies;
//using new to allocate the structure
Pizza_Analysis *ps = new Pizza_Analysis[3];
cout << "How many companies do you want to look at? ";
cin >> num_of_companies;
cin.get();
//the struct array at work
for(int i=0; i<num_of_companies; i++)
{
cout << "\n\nPlease enter company name. ";
cin.getline(ps<i>.company_name,35);
cout <<"\n\nPlease enter the diameter of the pizza. ";
cin >> ps<i>.dia_of_pizza;
cout <<"\n\nPlease enter the weight of the pizza. ";
cin >> ps<i>.weight_of_pizza;
cin.get();
}
cout << endl << endl;
//the struct array at work
// prints the input to screen
for(int i=0; i<3; i++)
{
cout << "Company Name : " << ps<i>.company_name << endl
<< "diameter of pizza : " << ps<i>.dia_of_pizza << endl
<< "Weight of pizza : " << ps<i>.weight_of_pizza << endl <<endl;
};
delete [] ps;
system("pause");//you may have to remove this depending on you compiler
return 0;
}
|