易百教程

结构体数据值组合

可以使用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()函数显示结构体的成员值。该函数在两行之间用反斜杠分割。