Printing the student ID and name using struct data type in C program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows 2003 Server Standard Edition

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Printing the student ID and name using struct data type

To show: How to use the struct data type in C programming for aggregate data type

 

// A simple structure program example

#include <stdio.h>

 

// struct definition

struct student{

char id_num[6];

char name[11];

char gender;

int age;

};

 

int main(void)

{

// struct declaration

struct student studno_1;

 

// studno_1.id_num = "A3214"; //Illegal, const char to char[]

// studno_1.name = "Smith"; //Illegal, const char to char[]

 

printf("First of all, get the size of the struct: %d\n", sizeof(struct student));

printf("Enter student ID num (5 max): ");

 

// scanf("%s", studno_1.id_num); // unsecure version

scanf_s("%s", studno_1.id_num, 24);

printf("Enter student name (10 max): ");

 

// scanf("%s", studno_1.name); // old, unsecure version

scanf_s("%s", studno_1.name, 11);

studno_1.gender = 'M';

studno_1.age = 30;

printf("\n------------------\n");

printf("ID number: %s\n", studno_1.id_num);

printf("Name : %s\n", studno_1.name);

printf("Gender : %c\n", studno_1.gender);

printf("Age : %d\n", studno_1.age);

printf("------------------\n");

return 0;

}

 

Output example:

 

First of all, get the size of the struct: 24

Enter student ID num (5 max): 2415

Enter student name (10 max): Maddona

------------------

ID number: 2415

Name : Maddona

Gender : M

Age : 30

------------------

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index