구조체란 무엇인가?
구조체(structure)는 서로 다른 데이터 타입의 항목들을 하나로 묶어 놓은 집합입니다. 여러 자료형으로 이루어진 복잡한 데이터 구조를 만들 때 매우 유용하며, C++에서는 struct 키워드를 사용하여 정의합니다.
예를 들어, 피트와 인치 단위의 거리를 표현하는 구조체는 다음과 같이 정의할 수 있습니다.
struct DistanceFI {
int feet;
int inch;
};위 구조체는 하나의 거리를 피트(feet)와 인치(inch)의 조합으로 표현합니다.
C++ 전체 코드 예제
다음은 C++에서 구조체를 사용하여 두 거리(피트-인치)를 더하는 완전한 프로그램입니다.
#include <iostream>
using namespace std;
struct DistanceFI {
int feet;
int inch;
};
int main() {
struct DistanceFI distance1, distance2, distance3;
cout << "Enter feet of Distance 1: "<<endl;
cin >> distance1.feet;
cout << "Enter inches of Distance 1: "<<endl;
cin >> distance1.inch;
cout << "Enter feet of Distance 2: "<<endl;
cin >> distance2.feet;
cout << "Enter inches of Distance 2: "<<endl;
cin >> distance2.inch;
distance3.feet = distance1.feet + distance2.feet;
distance3.inch = distance1.inch + distance2.inch;
if(distance3.inch > 12) {
distance3.feet++;
distance3.inch = distance3.inch - 12;
}
cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";
return 0;
}
실행 결과
위 프로그램을 실행하면 다음과 같은 출력을 확인할 수 있습니다.
Enter feet of Distance 1: 5
Enter inches of Distance 1: 9
Enter feet of Distance 2: 2
Enter inches of Distance 2: 6
Sum of both distances is 8 feet and 3 inches
코드 상세 설명
1. 구조체 정의
프로그램에서는 피트와 인치 단위의 거리를 저장하는 DistanceFI 구조체를 정의합니다. feet와 inch라는 두 개의 정수형 멤버 변수를 가집니다.
struct DistanceFI{
int feet;
int inch;
};2. 사용자 입력 받기
더할 두 거리의 값은 cin을 통해 사용자로부터 직접 입력받습니다. 첫 번째 거리의 피트와 인치, 그리고 두 번째 거리의 피트와 인치를 차례로 입력받아 각 구조체 변수에 저장합니다.
cout << "Enter feet of Distance 1: "<<endl;
cin >> distance1.feet;
cout << "Enter inches of Distance 1: "<<endl;
cin >> distance1.inch;
cout << "Enter feet of Distance 2: "<<endl;
cin >> distance2.feet;
cout << "Enter inches of Distance 2: "<<endl;
cin >> distance2.inch;
3. 거리 덧셈과 인치 자릿수 처리
두 거리의 피트와 인치를 각각 따로 더합니다. 이때 인치의 합이 12보다 크면 피트에 1을 더하고 인치에서 12를 빼주는데, 그 이유는 1피트 = 12인치이기 때문입니다. 예를 들어 15인치는 1피트 3인치로 변환됩니다.
distance3.feet = distance1.feet + distance2.feet;
distance3.inch = distance1.inch + distance2.inch;
if(distance3.inch > 12) {
distance3.feet++;
distance3.inch = distance3.inch - 12;
}
참고로, 입력되는 인치 값이 각각 12 미만이라면 인치의 합은 최대 23이므로 한 번의 if 검사로 충분합니다. 하지만 더 일반적인 처리를 원한다면 while(distance3.inch >= 12) 반복문을 사용하는 것도 좋은 방법입니다.
4. 결과 출력
마지막으로 계산된 거리의 피트와 인치 값을 cout으로 화면에 출력합니다.
cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";
마무리
이 예제는 구조체가 서로 연관된 데이터(피트와 인치)를 하나의 단위로 묶어 관리하는 데 얼마나 효과적인지 보여줍니다. 구조체를 활용하면 관련 데이터를 함수로 전달하거나 반환하기도 훨씬 간편해지므로, 실무에서도 복잡한 데이터를 다룰 때 널리 사용됩니다.