본문 바로가기
윤성우 열혈강의 C 정리

[ C 열혈강의 ] 22장 연습문제 : 구조체와 사용자정의 자료형1

by 어린왕자1234 2022. 7. 8.
// [ 문제22 - 1  : 구조체의 정의 ]  
// 문제1 : 
// 이름 주민번호 급여를 입력하는 구조체 선언 및 입출력

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct
{
	char name[20];
	char pid[20];
	int salary;
} Employee;

void inputData(Employee* ptr);
void outputData(Employee* ptr);


int main(void)
{
	Employee person;

	inputData(&person);
	outputData(&person);
}

void inputData(Employee* ptr)
{
	printf("이름 입력 :");
	scanf_s("%s", ptr->name,20);
	printf("주민번호 입력 :");
	scanf_s("%s", ptr->pid,20);
	printf("급여 입력 :");
	scanf_s("%d", &(ptr->salary));
}
void outputData(Employee* ptr)
{
	printf("이름 입력 : %s\n", ptr->name);
	printf("이름 입력 : %s\n", ptr->pid);
	printf("이름 입력 : %d\n", ptr->salary);
}

[ 방법1 ]

// [ 문제22 - 2  : 구조체 배열의 선언 ]  
// 문제1 : 
// 이름 주민번호 급여를 입력하는 구조체 배열 선언 및 입출력

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct
{
	char name[20];
	char pid[20];
	int salary;
} Employee;

void inputData(Employee* ptr);
void outputData(Employee* ptr);


int main(void)
{
	Employee person[3];

	for (int i = 0; i < 3; i++)
	{
		printf("[ 데이터 입력 ]\n");
		inputData(&person[i]);
	}
	for (int i = 0; i < 3; i++)
	{
		printf("[ 출력 결과 ]\n");
		outputData(&person[i]);
	}
}


void inputData(Employee* ptr)
{
	printf("이름 입력 :");
	scanf_s("%s", ptr->name, 20);
	printf("주민번호 입력 :");
	scanf_s("%s", ptr->pid, 20);
	printf("급여 입력 :");
	scanf_s("%d", &(ptr->salary));
}
void outputData(Employee* ptr)
{
	printf("이름 : %s\n", ptr->name);
	printf("주민번호 : %s\n", ptr->pid);
	printf("급여 : %d\n", ptr->salary);
}

 

[ 방법2 ]

// [ 문제22 - 2  : 구조체 배열의 선언 ]  
// 문제1 : 
// 이름 주민번호 급여를 입력하는 구조체 배열 선언 및 입출력

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct
{
	char name[20];
	char pid[20];
	int salary;
} Employee;

void inputData(Employee* ptr, int len);
void outputData(Employee* ptr, int len);


int main(void)
{
	Employee person[3];
	inputData(person, sizeof(person)/sizeof(Employee));
	outputData(person, sizeof(person) / sizeof(Employee));
}


void inputData(Employee* ptr, int len)
{
	printf("[ 데이터 입력 ]\n");
	for (int i = 0; i < len; i++)
	{
		printf("이름 입력 :");
		scanf_s("%s", &(ptr[i].name), 20);
		printf("주민번호 입력 :");
		scanf_s("%s", &(ptr[i].pid), 20);
		printf("급여 입력 :");
		scanf_s("%d", &(ptr[i].salary));
	}
}
void outputData(Employee* ptr, int len)
{
	printf("[ 출력 결과 ]\n");
	for (int i = 0; i < 3; i++)
	{
		printf("이름 : %s\n", ptr[i].name);
		printf("주민번호 : %s\n", ptr[i].pid);
		printf("급여 : %d\n", ptr[i].salary);		
	}
}