可以使用struct
将相关数据组合在一起。
示例代码
#include <stdio.h>
int main()
{
struct player
{
char name[32];
int highscore;
};
struct player game_player;
printf("Enter the player's name: ");
scanf("%s",game_player.name);
printf("Enter their high score: ");
scanf("%d",&game_player.highscore);
printf("Player %s has a high score of %d\n", game_player.name,game_player.highscore);
return(0);
}
执行上面示例代码,得到以下代码:
Enter the player's name: Curry
Enter their high score: 198
Player Curry has a high score of 198
首先声明player
结构。这个结构有两个成员 - 一个char
数组(字符串)和int
- 就像任何其他变量一样声明。然后它为play
结构体game_player
声明一个新变量。之后使用scanf()
以字符串值填充game_player
结构体变量的name
成员。
它使用scanf()
为game_player
结构体中的highscore
成员赋值。使用printf()
函数显示结构体的成员值。该函数在两行之间用反斜杠分割。