전공/C
과제11 - final (2)
yha97
2021. 6. 22. 15:53
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// declaring structure
struct person{
int id;
char name[10];
double point;
};
int cnt=0; // global variable for total structures
struct person add(){ // function add returning struct person after entering elements
struct person temp;
printf("Enter ID : ");
scanf("%d", &temp.id);
printf("Enter Name: ");
scanf("%s", temp.name);
printf("Enter Reward_point: ");
scanf("%lf", &temp.point);
return temp; // returning struct person
}
void display(struct person *p){ // displaying function with person pointer argument
int i=0;
printf("ID Name Reward_point\n");
// printing elements of structures
for(i=0; i<cnt; i++)
printf("%d %s %lf\n", p[i].id, p[i].name, p[i].point); // 출력
}
void update(struct person *p){ // editing elements with person pointer
int n, i;
int temp1;
double temp2;
printf("Enter the customer ID to edit the record : "); // entering id to edit
scanf("%d", &n);
for(i=0; i<cnt; i++){
if(n==p[i].id){
printf("Name : %s\n", p[i].name);
printf("Reward_point : %lf\n", p[i].point);
printf("Enter new name : "); // entering from user and editing
scanf("%s", p[i].name);getchar();
printf("Enter new reward_point : ");
scanf("%lf", &p[i].point);
return;
}
}
printf("There's no matching customer!!\n'"); // if no matching with entered id
return;
}
void Exit(){ // exit and printing message
printf("\n\nBye!");
}
int main(){
struct person* ptr = malloc(sizeof(struct person) * 10); // memory allocation with struct person
int i=0;
while(1){
// printing main menu
int select;
printf("1:Add\n");
printf("2:Display\n");
printf("3:Update\n");
printf("4:Exit\n");
scanf("%d", &select);
switch(select){
case 1:{
ptr[cnt] = add(); // returning struct person with counting total strucutre
cnt++; // increasing total number of person
break;
}
case 2:{
display(ptr); // displaying (sending pointer as argument)
break;
}
case 3:
update(ptr); // updating (sending pointer as argument)
break;
case 4:{ // end of program
free(ptr); // deallocating memory
Exit();
return 0;
}
default: // if no matching number from user
printf("Enter 1 ~ 4\n");
}
}
return 0;
}
구조체 배열을 통해 유저 데이터를 만드는 프로그램이다.
Q1보다는 비교적 수월했고 동적할당을 통해 문제를 해결할 수 있었다.
전반적으로 구조체와 동적 할당 개념을 알고 있었다면 그렇게 오래 걸리지 않았을 것이라고 생각한다.