Language/C++

📌예제 - 온라인 쇼핑몰 주문 관리 시스템

e-cko 2025. 11. 1. 19:00
반응형

문제: 온라인 쇼핑몰 주문 관리 시스템

1. 프로그램 개요

온라인 쇼핑몰에서 상품과 주문을 관리하는 프로그램을 작성하세요.

주요 기능은 상품 등록, 주문 생성, 주문 조회, 전체 주문 요약, 데이터 저장/로드입니다.


2. 클래스 구조

2-1. Product 클래스

상품 정보 관리

속성:

상품ID (int)

이름 (std::string)

가격 (double)

 

2-2. Order 클래스

주문 정보 관리

속성:

주문ID (int)

주문한 상품 리스트 (상품ID → 수량)

총 금액 계산

기능:

주문 추가

주문 총액 계산

가상 함수 printSummary() 구현

RegularOrder ExpressOrder에서 다르게 출력

 

2-3. Customer 클래스

고객 정보 관리

속성:

고객ID (int)

이름 (std::string)

주문 리스트 (Order 객체 리스트)

기능:

주문 추가

고객 주문 출력


3. 프로그램 기능 요구 사항

 

3-1. 상품 등록

Product 객체 생성 후 상품 목록에 추가

STL std::map<int, Product> 사용 (상품ID 기준)

 

3-2. 주문 생성

고객 이름 입력

신규 고객이면 새 Customer 객체 생성

주문할 상품ID와 수량 입력

주문 객체 생성 후 고객 주문 리스트에 추가

총 금액 계산

존재하지 않는 상품ID 입력 시 사용자 정의 예외 발생

 

3-3. 주문 정보 출력

특정 고객의 모든 주문 출력

전체 고객 주문 요약 출력 가능

 

3-4. 파일 입출력

프로그램 종료 시 모든 주문과 고객 정보를 orders.txt에 저장

프로그램 시작 시 파일이 존재하면 기존 정보 불러오기


4. 고급 요구사항

다형성: Order 클래스의 printSummary()를 가상 함수로 구현 → RegularOrder, ExpressOrder에서 다르게 출력

 

스마트 포인터 사용: std::shared_ptr / std::unique_ptr

 

STL 알고리즘 활용: ) std::accumulate로 주문 총액 계산


5. 예상 실행 예시

===== 쇼핑몰 주문 관리 시스템 =====

1. 상품 등록

2. 주문 생성

3. 고객 주문 조회

4. 전체 주문 요약

5. 종료

선택: 1

 

상품 이름: 스마트폰

가격: 800000

상품 등록 완료. 상품ID: 101

 

===== 쇼핑몰 주문 관리 시스템 =====

1. 상품 등록

2. 주문 생성

3. 고객 주문 조회

4. 전체 주문 요약

5. 종료

선택: 2

 

고객 이름: 김철수

주문할 상품ID: 101

수량: 2

주문 생성 완료. 총 금액: 1600000

 

===== 쇼핑몰 주문 관리 시스템 =====

1. 상품 등록

2. 주문 생성

3. 고객 주문 조회

4. 전체 주문 요약

5. 종료

선택: 3

 

고객: 김철수

주문ID: 1001

 - 스마트폰 x2 : 1600000

총 주문 금액: 1600000


스크롤을 내리면 제가 직접 작성한 코드가 있습니다.

먼저 직접 풀어보시고 참고만 해주시길 바라며, 피드백 환영입니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형

 

 

 

 

 

 

 

 

 

 

 


Class.h

#pragma once

#include <string>

#include <memory>

#include <map>

 

class Product {

           unsigned short id;

           std::string name;

           unsigned int price;

public:

           Product(short id, std::string name, int price) :id(id), name(name), price(price){}

           unsigned short getId();

           std::string getName();

           unsigned int getPrice();

           void showProduct();

};

 

class Order {

           unsigned short userId;

           std::map<std::shared_ptr<Product>, unsigned int> odP;

           unsigned int totalPrice;

public:

           Order(short userId, std::map<std::shared_ptr<Product>, unsigned int>& odP, int totalPrice) :userId(userId), odP(odP), totalPrice(totalPrice) {}

           std::map<std::shared_ptr<Product>, unsigned int>& getOdp();

           void showOrder();

           virtual void printSummary() const=0;

};

 

class RegularOrder : public Order {

public:

           RegularOrder(short id, std::map<std::shared_ptr<Product>, unsigned int>& odP, int totalPrice) :Order(id, odP, totalPrice) {}

           void printSummary() const;

};

 

class ExpressOrder: public Order {

public:

           ExpressOrder(short id, std::map<std::shared_ptr<Product>, unsigned int>& odP, int totalPrice) :Order(id, odP, totalPrice) {}

           void printSummary() const;

};

 

class Customer {

           unsigned short userId;

           std::string name;

           Order* od;

public:

           Customer(short userId, std::string name) :userId(userId), name(name){}

           void addOrder(Order* od);

           std::string getName();

           unsigned short getUid();

           Order* getOrder();

           void showCustomer();

};


Class.cpp

#include "Class.h"

#include <iostream>

using namespace std;

 

unsigned short Product::getId()

{

           return id;

}

 

std::string Product::getName()

{

           return name;

}

 

unsigned int Product::getPrice()

{

           return price;

}

 

void Product::showProduct()

{

           cout << "상품 ID: " << id << endl;

           cout << "상품명: " << name << endl;

           cout << "상품 가격: " << price << endl;

}

 

std::map<std::shared_ptr<Product>, unsigned int>& Order::getOdp() {

           return odP;

}

 

void Order::showOrder()

{

           cout << "고객 ID: " << userId << endl;

           for (auto& od : odP) {

                      cout << "상품명: " << od.first->getName()<< ", 상품가격: " << od.first->getPrice() <<", 상품 수량 : " << od.second<<", 해당 상품 주문금액: " << od.first->getPrice()* od.second << endl<<endl;

           }

           cout << "총 금액: " << totalPrice << endl<<endl;

}

 

void RegularOrder::printSummary() const

{

           cout << "[일반배송]" << endl;

}

 

void ExpressOrder::printSummary() const

{

           cout << "[특급배송]" << endl;

}

 

void Customer::addOrder(Order* od) {

           this -> od = od;

}

 

string Customer::getName()

{

           return name;

}

 

unsigned short Customer::getUid()

{

           return userId;

}

 

Order* Customer::getOrder() {

           return od==nullptr?nullptr:od;

}

 

 

void Customer::showCustomer()

{

           od->showOrder();

}


Shopping.h

#pragma once

#include "Class.h"

#include <vector>

 

class Shopping {

           unsigned short pNumber=100;

           std::vector<std::shared_ptr<Product>> product;

           std::vector<std::unique_ptr<Order>> order;

           std::vector<std::unique_ptr<Customer>> customer;

public:

           void init();

           void addProduct();

           void addOrder();

           void getCustomer();

           void allCustomer();

};


Shopping.h

#include "Shopping.h"

#include <iostream>

#include <algorithm>

#include <fstream>

 

using namespace std;

 

void Shopping::init()

{

           cout << "상품 목록 불러오는중!!" << endl<<endl;

           ifstream fin("product.txt");

           if (!fin)

                      return;

           else {

                      short pId;

                      string pName;

                      int price;

                      while(fin>>pId>>pName>>price)

                                 product.push_back(make_shared<Product>(pId, pName, price));

 

                      pNumber = pId + 1;

           }

           fin.close();

 

           cout << "고객 목록 불러오는중!!" << endl << endl;

           fin.open("customer.txt");

           if (!fin)

                      return;

           else {

                      short uId;

                      string name;

                      while (fin >> uId >> name)

                                 customer.push_back(make_unique<Customer>(uId, name));

           }

           fin.close();

 

           cout << "주문 목록 불러오는중!!" << endl << endl;

           fin.open("order.txt");

           if (!fin)

                      return;

           else {

                      int uId;

                      short pId;

                      int qty;

                      int totalPrice;

                      short n;

                      short addMap;

                      map<shared_ptr<Product>, unsigned int> odP;

                      while (fin >> uId >> totalPrice >> n >> addMap) {

                                 for (int i = 0; i < addMap; ++i) {

                                             fin >> pId >> qty;

                                             vector<shared_ptr<Product>>::iterator pd = find_if(product.begin(), product.end(),

                                              [pId](const shared_ptr<Product>& p) {return pId == p->getId(); });

                                             odP[*pd] = qty;

                                            

                                 }

                                 n == 2 ? order.push_back(std::make_unique<ExpressOrder>(uId, odP, totalPrice))

                                             : order.push_back(std::make_unique<RegularOrder>(uId, odP, totalPrice));

 

                                 vector<unique_ptr<Customer>>::iterator user = find_if(customer.begin(), customer.end(),

                                             [uId](const unique_ptr<Customer>& u) {return u->getUid() == uId; });

                                 if (user != customer.end())

                                             (*user)->addOrder(order.back().get());

                                 odP.clear();

                      }

           }

           fin.close();

}

 

void Shopping::addProduct()

{

           string name;

           int price;

 

           cout<< endl << "상품 이름: ";

           cin >> name;

           while (1) {

                      cout << "상품 가격: ";

                      cin >> price;

                      if (cin.fail() || price <= 0) {

                                 cin.clear(); // 에러 플래그 초기화

                                 cin.ignore(10000, '\n'); // 버퍼 비우기

                                 cout << "올바른 가격를 입력하세요!\n";

                                 continue;

                      }

                      ofstream fout("product.txt", ios::app);

                      if (!fout)

                                 cout << "상품목록 저장 실패 다시 등록해주세요" << endl;

                      else {

                                 fout << pNumber << " " << name << " " << price<<endl;

                                 fout.close();

                                 product.push_back(make_shared<Product>(pNumber, name, price));

                                 cout << endl << "[상품등록 완료]" << endl << "상품ID: " << pNumber++ << endl << endl;

                                 break;

                      }

           }

}

 

void Shopping::addOrder()

{

           short userId=0;

           vector<unique_ptr<Customer>>::iterator user;

           while (userId==0) {

                      cout<<endl << "고객명: ";

                      string name;

                      cin >> name;

                      bool check = any_of(name.begin(), name.end(), [](char ch)

                                 { return isdigit(static_cast<unsigned char>(ch)) || ispunct(static_cast<unsigned char>(ch));  });

                      if (check) {

                                 cout << "이름에 숫자나 특수문자는 입력할 수 없습니다." << endl;

                                 continue;

                      }

                      user = find_if(customer.begin(), customer.end(),

                                 [name](const unique_ptr<Customer>& u) {return u->getName() == name; });

                      if (user != customer.end()) {

                                 userId = (*user)->getUid();

                      }

                      else {

                                 if (!customer.empty()) {

                                             userId = customer.back()->getUid() + 1;

                                            customer.push_back(make_unique<Customer>(userId, name));

                                 }

                                 else {

                                             userId = 1000;

                                            customer.push_back(make_unique<Customer>(userId, name));

                                 }

                                 ofstream fout("customer.txt", ios::app);

                                 if (!fout) {

                                             cout << "회원목록 저장 실패 다시 등록해주세요" << endl;

                                             customer.pop_back();

                                             continue;

                                 }

                                 else {

                                             fout << userId << " " << name << endl;

                                             fout.close();

                                 }

                                 user = customer.end() - 1;

                      }

           }

          

           map<shared_ptr<Product>, unsigned int> odP2;

           int totalPrice=0;

           while (1) {

                      cout << "주문할 상품ID: ";

                      short pId;

                      cin >> pId;

                      if (cin.fail()) {

                                 cin.clear(); // 에러 플래그 초기화

                                 cin.ignore(10000, '\n'); // 버퍼 비우기

                                 cout << "올바른 가격를 입력하세요!\n";

                                 continue;

                      }

                      vector<shared_ptr<Product>>::iterator pd = find_if(product.begin(), product.end(),

                                 [pId](const shared_ptr<Product>& p) {return pId == p->getId(); });

                      if (pd != product.end()) {

                                 while (1) {

                                             cout << "수량: ";

                                             cin >> pId;

                                             if (cin.fail()) {

                                                        cin.clear(); // 에러 플래그 초기화

                                                        cin.ignore(10000, '\n'); // 버퍼 비우기

                                                        cout << "올바른 가격를 입력하세요!\n";

                                                        continue;

                                             }

                                             break;

                                 }

                                

                                 odP2[*pd] = pId;

                                 totalPrice += (*pd)->getPrice() * pId;

                      }

                      else {

                                 cout << "해당 상품은 존재하지 않습니다." << endl << endl;

                                 continue;

                      }

                      cout << "다른 상품 주문하려면 1을 입력해주세요." << endl <<"주문을 마감하시려면 1을 제외한 아무 키나 눌러주세요." << endl << "선택: ";

                      cin >> pId;

                      if (pId == 1)

                                 continue;

                      else

                                 break;

           }

           if ((*user)->getOrder()) {

                      ifstream fin("order.txt");

                      if (!fin) {

                                 cout << "주문목록 저장 실패 다시 등록해주세요" << endl;

                                 return;

                      }

                      else {

                                 std::vector<std::string> lines;

                                 std::string line;

                                 while (getline(fin, line))

                                             lines.push_back(line);

                                 fin.close();

 

                                 short n=0;

                                 for (int i = 0; i < lines.size(); ++i) {

                                             if (lines[i].find(std::to_string(userId)) != std::string::npos) {

                                                        n = i+1;

                                             }

                                 }

                                 map<shared_ptr<Product>, unsigned int>& odP = (*user)->getOrder()->getOdp();

                                 for (const auto& p : odP2) {

                                             std::string orderLine = std::to_string(p.first->getId()) + " " + std::to_string(p.second);

                                             lines.insert(lines.begin() + n++, orderLine);

                                             odP[p.first] += p.second;

                                 }

                                 std::ofstream fout("order.txt"); // append 제거 → 전체 덮어쓰기

                                 for (const auto& l : lines)

                                             fout << l << "\n";

                                 fout.close();

                      }

           }

           else {

                      short c;

                      while (1) {

                                 cout << "1. 일반배송 2. 특급 배송" << endl << "선택: ";

                                 cin >> c;

                                 if (c < 0 || c>2)

                                             continue;

                                 break;

                      }

                     

                                 ofstream fout("order.txt", ios::app);

                                 if (!fout) {

                                             cout << "주문목록 저장 실패 다시 등록해주세요" << endl;

                                             return;

                                 }

                                 else {

                                             fout << userId << " " << totalPrice << " " << c << " " << odP2.size() << endl;

                                             for (const auto& p : odP2) {

                                                        fout << p.first->getId() << " " << p.second << endl;

                                             }

                                             fout.close();

                                 }

                     

                     

                      c==2?

                      order.push_back(std::make_unique<ExpressOrder>(userId, odP2, totalPrice += 3000))

                      : order.push_back(std::make_unique<RegularOrder>(userId, odP2, totalPrice));

 

                      (*user)->addOrder(order.back().get());

           }

           cout<<endl<< "주문 생성 완료. 총 금액: " << totalPrice << endl<<endl;

}

 

void Shopping::getCustomer()

{

           string name;

           while (1) {

                      cout <<endl <<"이름을 입력해주세요: ";

                      cin >> name;

                      bool check = any_of(name.begin(), name.end(), [](char ch)

                                 { return isdigit(static_cast<unsigned char>(ch)) || ispunct(static_cast<unsigned char>(ch));  });

                      if (check) {

                                 cout << "이름에 숫자나 특수문자는 입력할 수 없습니다." << endl;

                                 continue;

                      }

                      break;

           }

           vector<std::unique_ptr<Customer>>::iterator user = std::find_if(customer.begin(), customer.end(), [name](const std::unique_ptr<Customer>& u) {return u->getName() == name; });

           if (user != customer.end()) {

                      (*user)->showCustomer();

           }

           else {

                      cout << "주문한 내역이 없습니다." << endl<<endl;

           }

}

 

void Shopping::allCustomer() {

           for (auto& u : customer) {

                      u->showCustomer();

                      cout << endl;

           }

           cout << endl<<endl;

}


main.cpp

#include <iostream>

#include "Class.h"

#include "Shopping.h"

 

using namespace std;

 

void main() {

           Shopping s;

           short c;

           s.init();

           while (1) {

                      cout << "메뉴를 선택하세요." << endl;

                      cout << "1. 상품 등록" << endl;

                      cout << "2. 주문 생성" << endl;

                      cout << "3. 고객 주문 조회" << endl;

                      cout << "4. 전체 주문 조회" << endl;

                      cout << "5. 종료" << endl;

                      cout << "선택: ";

                      cin >> c;

                      switch (c)

                      {

                      case 1:

                                 s.addProduct();

                                 break;

                      case 2:

                                 s.addOrder();

                                 break;

                      case 3:

                                 s.getCustomer();

                                 break;

                      case 4:

                                 s.allCustomer();

                                 break;

                      case 5:

                                 return;

                      default:

                                 cout << "올바른 메뉴를 선택해주세요!" << endl;

                                 break;

                      }

           }

}

반응형