C++编程求助

2024-11-30 06:35:50
推荐回答(3个)
回答1:

你的赋值 有问题改好了:
#include
using namespace std;
struct CandyBar
{
char pinpai[20];
double zhongliang;
int kaluli;
};
int main()
{
CandyBar *snack = new CandyBar[3];
CandyBar person[3]=
{
{"Moncha Munch1",2.3,350 } ,
{"Moncha Munch2",2.4,351 } ,
{"Moncha Munch3",2.5,352 }

};

snack[0]=person[0];//结构的赋值
snack[1]=person[1];
snack[2]=person[2];

int i;
for(i=0; i<3; i++)
{
cout << "Pinpai: " << snack[i].pinpai <cout << "zhongliang: " << snack[i].zhongliang <cout << "kaluli: " << snack[i].kaluli <}
delete [] snack;
return 0;
}

不用NEW也可以实现的:
#include
using namespace std;
struct CandyBar
{
char pinpai[20];
double zhongliang;
int kaluli;
};
int main()
{

CandyBar person[3]=
{
{"Moncha Munch1",2.3,350 } ,
{"Moncha Munch2",2.4,351 } ,
{"Moncha Munch3",2.5,352 }

};

CandyBar *snack = person;

int i;
for(i=0; i<3; i++)
{
cout << "Pinpai: " << snack[i].pinpai <cout << "zhongliang: " << snack[i].zhongliang <cout << "kaluli: " << snack[i].kaluli <}

return 0;
}

当然 还可以这样赋值
#include
#include
using namespace std;
struct CandyBar
{
char pinpai[20];
double zhongliang;
int kaluli;
};
int main()
{
CandyBar * snack = new CandyBar [3];
snack[0].kaluli=350;
strcpy(snack[0].pinpai,"Moncha Munch");
snack[0].zhongliang=2.3 ;

snack[1].kaluli=3501;
strcpy(snack[1].pinpai,"Moncha Munch1");
snack[1].zhongliang=2.31 ;

snack[2].kaluli=3502;
strcpy(snack[2].pinpai,"Moncha Munch2");
snack[2].zhongliang=2.32 ;

int i;
for(i=0; i<3; i++)
{
cout << "Pinpai: " << snack[i].pinpai <cout << "zhongliang: " << snack[i].zhongliang <cout << "kaluli: " << snack[i].kaluli <}
delete [] snack;
return 0;
}

回答2:

数组只能在初始化的时候利用大括号整体赋值,

现在你可以换一种方法来给结构体成员赋值

比如
strcpy(snack[0].pinpai,"Moncha Munch");
snack[0].zhongliang = 2.3;
snack[0].kaluli = 350;

回答3:

我是不知道啦
你自己一个一个赋值吧