C - Group value together with struct

Introduction

You can use struct to group related data together.

Demo

#include <stdio.h> 

int main() /*  w  ww .  ja v a2s  .  c om*/
{ 
    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); 
}

Result

First we declare the player structure.

This structure has two members - a char array (string) and int - declared just like any other variables.

Then it declares a new variable for the player structure, game_player.

After that it uses scanf() to fill the name member for the game_player structure variable with a string value.

It uses scanf() to assign a value to the highscore member in the game_player structure.

The structure's member values are displayed by using a printf() function.

The function is split between two lines with a backslash.

Related Topic