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

本文介绍了一个使用C++实现的动态数组案例,该案例通过结构体定义了糖果条的信息,并利用动态内存分配的方式创建了一个动态数组。用户可以输入数组大小及每个元素的具体信息,如种类、重量和热量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值