创建结构candybar,要求用new来动态分配结构数组

来源:互联网 发布:淘宝买仿真 编辑:程序博客网 时间:2024/06/12 01:05

#include <iostream>

struct CandyBar
{
 char kind[20];
 float weight;
 int cal;
};

int main()
{
 using namespace std;
 int size;
 cout<<"the size is: ";

 cin>>size;//数组的元素数
 cin.get();
 CandyBar *ps=new CandyBar[size];//创建一个动态数组

 

 //从键盘读取各项的值.....
 for(int i=0;i<size;i++)
 {
  cout<<"Enter the kind: ";
  cin.getline(ps[i].kind,20);    

//如果不想从键盘读取kind的值,可使用strcpy(ps[i].kind,"kindname");直接对kind赋值.使用ps[i].kind="kindname";会报错!!
  
  cout<<"Enter the weight: ";
  cin>>ps[i].weight;
  cin.get();
  cout<<"Enter the cal: ";
  cin>>ps[i].cal;
  cin.get();
  cout<<"ps["<<i<<"].kind:"<<ps[i].kind<<"  "<<endl;
  cout<<"ps["<<i<<"].weight:"<<ps[i].weight<<"  "<<endl;
  cout<<"ps["<<i<<"].cal:"<<ps[i].cal<<"  "<<endl;
 }

 return 0;
}