C++输出字符数组乱码

```
#include <iostream>
using namespace std;

struct CandyBar
{
char name[50];
double weight;
int hot;
};

void Set(CandyBar &candy, const char *c = "Milennium Munch", const double &w = 2.85, const int &h = 350);
void Show(const CandyBar &candy);

int main()
{
CandyBar candyOne, candyTwo;
Set(candyOne);
Set(candyTwo, "CandyTwo", 3.50, 285);
Show(candyOne);
Show(candyTwo);
return 0;
}

void Set(CandyBar & candy, const char * c, const double & w, const int & h)
{
int n = strlen(c);
int i;
for (i = 0; i < n; i++)
{
candy.name[i] = c[i];
}
candy.name[i + 1] = '\0';
candy.weight = w;
candy.hot = h;
}

void Show(const CandyBar &candy)
{
cout << candy.name << " " << candy.weight << " " << candy.hot << endl;
}

```
最后打印出来的是Milennium Munch?
只有这么一行,后面的东西也全都不见了,当我把Show()函数改成

```
void Show(const CandyBar &candy)
{
cout << candy.name << endl << candy.weight << endl << candy.hot << endl;
}

```

打印:
Milennium Munch
2.85
350
CandyTwo
3.5
285
打印的便正常了
这是怎么回事

梦里花落0921
浏览 1110回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP