您的位置:首页 > 其它

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

2009-10-15 18:22 441 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: