[42Seoul] CPP Module 00 - ex02

수빈·2022년 1월 2일
0

42CPP

목록 보기
4/11
post-thumbnail
  • Exercise02 : The Job Of Your Dreams 서브젝트에서 제공하는 Account.hppmain 이 포함된 test.cpp 를 제공함. 19920104_091532.log 를 참고하여 Account.cpp 를 작성할 것.

Account.hpp

// ************************************************************************** //
//                                                                            //
//                Account.hpp for GlobalBanksters United                //
//                Created on  : Thu Nov 20 19:43:15 1989                      //
//                Last update : Wed Jan 04 14:54:06 1992                      //
//                Made by : Brad "Buddy" McLane <bm@gbu.com>                  //
//                                                                            //
// ************************************************************************** //

#pragma once
#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__

// ************************************************************************** //
//                               Account Class                                //
// ************************************************************************** //

class Account {

public:

	typedef Account		t;

	static int	getNbAccounts( void );
	static int	getTotalAmount( void );
	static int	getNbDeposits( void );
	static int	getNbWithdrawals( void );
	static void	displayAccountsInfos( void );

	Account( int initial_deposit );
	~Account( void );

	void	makeDeposit( int deposit );
	bool	makeWithdrawal( int withdrawal );
	int		checkAmount( void ) const;
	void	displayStatus( void ) const;

private:

	static int	_nbAccounts;
	static int	_totalAmount;
	static int	_totalNbDeposits;
	static int	_totalNbWithdrawals;

	static void	_displayTimestamp( void );

	int				_accountIndex;
	int				_amount;
	int				_nbDeposits;
	int				_nbWithdrawals;

	Account( void );

};

// ************************************************************************** //
// vim: set ts=4 sw=4 tw=80 noexpandtab:                                      //
// -*- indent-tabs-mode:t;                                                   -*-
// -*- mode: c++-mode;                                                       -*-
// -*- fill-column: 75; comment-column: 75;                                  -*-
// ************************************************************************** //

#endif /* __ACCOUNT_H__ */

test.cpp

// ************************************************************************** //
//                                                                            //
//                tests.cpp for GlobalBanksters United                        //
//                Created on  : Thu Nov 20 23:45:02 1989                      //
//                Last update : Wed Jan 04 09:23:52 1992                      //
//                Made by : Brad "Buddy" McLane <bm@gbu.com>                  //
//                                                                            //
// ************************************************************************** //

#include <vector>
#include <algorithm>
#include <functional>
#include "Account.hpp"

int		main( void ) {

	typedef std::vector<Account::t>							  accounts_t;
	typedef std::vector<int>								  ints_t;
	typedef std::pair<accounts_t::iterator, ints_t::iterator> acc_int_t;

	int	const				amounts[]	= { 42, 54, 957, 432, 1234, 0, 754, 16576 };
	size_t const			amounts_size( sizeof(amounts) / sizeof(int) );
	accounts_t				accounts( amounts, amounts + amounts_size );
	accounts_t::iterator	acc_begin	= accounts.begin();
	accounts_t::iterator	acc_end		= accounts.end();

	int	const			d[]			= { 5, 765, 564, 2, 87, 23, 9, 20 };
	size_t const		d_size( sizeof(d) / sizeof(int) );
	ints_t				deposits( d, d + d_size );
	ints_t::iterator	dep_begin	= deposits.begin();
	ints_t::iterator	dep_end		= deposits.end();

	int	const			w[]			= { 321, 34, 657, 4, 76, 275, 657, 7654 };
	size_t const		w_size( sizeof(w) / sizeof(int) );
	ints_t				withdrawals( w, w + w_size );
	ints_t::iterator	wit_begin	= withdrawals.begin();
	ints_t::iterator	wit_end		= withdrawals.end();

	Account::displayAccountsInfos();
	std::for_each( acc_begin, acc_end, std::mem_fun_ref( &Account::displayStatus ) );

	for ( acc_int_t it( acc_begin, dep_begin );
		  it.first != acc_end && it.second != dep_end;
		  ++(it.first), ++(it.second) ) {

		(*(it.first)).makeDeposit( *(it.second) );
	}

	Account::displayAccountsInfos();
	std::for_each( acc_begin, acc_end, std::mem_fun_ref( &Account::displayStatus ) );

	for ( acc_int_t it( acc_begin, wit_begin );
		  it.first != acc_end && it.second != wit_end;
		  ++(it.first), ++(it.second) ) {

		(*(it.first)).makeWithdrawal( *(it.second) );
	}

	Account::displayAccountsInfos();
	std::for_each( acc_begin, acc_end, std::mem_fun_ref( &Account::displayStatus ) );

	return 0;
}

// ************************************************************************** //
// vim: set ts=4 sw=4 tw=80 noexpandtab:                                      //
// -*- indent-tabs-mode:t;                                                   -*-
// -*- mode: c++-mode;                                                       -*-
// -*- fill-column: 75; comment-column: 75;                                  -*-
// ************************************************************************** //

Account.cpp

void	Account::_displayTimestamp(void)
{
}

void Account::displayAccountsInfos()
{
}

Account::Account(int initial_deposit)
{
}

void	Account::displayStatus( void ) const
{
}

void Account::makeDeposit( int deposit )
{
}

bool Account::makeWithdrawal( int withdrawal )
{
}

Account::~Account()
{
}

hpp에 선언된 함수들이 test.cpp에서 어떻게 출력이 되는지 확인하기 위해 함수 선언만 냅다 넣은 후 cmd 로그를 출력했다.

이제 저 함수 순서에 맞게 log 파일을 비교하며 만들 것이다.

void	Account::_displayTimestamp(void)
{
	time_t	t_stamp;
	char	buff[16];

	time(&t_stamp);
	strftime(buff, sizeof(buff), "%Y%m%d_%H%M%S", localtime(&t_stamp));
	std::cout << "[" << buff << "]";
}

log파일에 있는 시간 그대로 출력해야 하는 건가? 싶었는데 그냥 프로그램 실행 시간을 출력하면 돼서 ctime의 함수인 time()을 활용하기로 했다. time_t 구조체(시간을 다루는데 필요한 정보가 저장됨)에 time()으로 초 단위의 시간을 부여하고, strftime()으로 원하는 출력 양식으로 표현할 수 있다. 해당 함수로 time_t를 지정한 양식으로 변환시켜주는 기능이다. (참고) localtime()으로 초 단위의 시간을 현재 시간으로 출력했다.

Account::Account(int initial_deposit)
{
	_accountIndex = Account::_nbAccounts;
	_amount = initial_deposit;
	_nbDeposits = 0;
	_nbWithdrawals = 0;
	_displayTimestamp();
	std::cout << " index:" << _accountIndex << ";";
	std::cout << "amount:" << _amount << ";";
	std::cout << "created" << std::endl;
	Account::_nbAccounts++;
	Account::_totalAmount += _amount;
}

log의 제일 첫 부분을 담당한다. 정보들을 생성했음을 알리는 함수다.

void Account::displayAccountsInfos()
{
	_displayTimestamp();
	std::cout << " accounts:" << Account::_nbAccounts << ";";
	std::cout << "total:" << Account::_totalAmount << ";";
	std::cout << "deposits:" << Account::_totalNbDeposits << ";";
	std::cout << "withdrawals:" << Account::_totalNbWithdrawals << std::endl;
}

[20220103_011945] accounts:8;total:20049;deposits:0;withdrawals:0 으로 중간 집계 느낌으로 출력되는 내용이 있다. 어.. getter로 접근하라는 것 같았지만 까먹었다..^^!

void Account::makeDeposit( int deposit )
{
	int	p_amount;

	p_amount = _amount;
	_amount += deposit;
	_nbDeposits++;
	_displayTimestamp();
	std::cout << " index:" << _accountIndex << ";";
	std::cout << "p_amount:" << p_amount << ";";
	std::cout << "deposits:" << deposit << ";";
	std::cout << "amount:" << _amount << ";";
	std::cout << "nb_deposits:" << _nbDeposits << std::endl;
	Account::_totalNbDeposits++;
	Account::_totalAmount += deposit;
}

deposit 값이 들어오면서 amount 값에 변동이 생겼다.
인덱스; 금액; 예치금; 금액 + 예치금; 예치금 횟수; 로 이해했으니 새로운 인자 p_amount을 선언해 함수를 만들었다. displayAccountsInfos에서 활용하기 위해 total인자도 값을 부여.

bool Account::makeWithdrawal( int withdrawal )
{
	int	p_amount;

	p_amount = _amount;
	_amount = _amount - withdrawal;
	_displayTimestamp();
	std::cout << " index:" << _accountIndex << ";";
	std::cout << "p_amount:" << p_amount << ";";
	if (_amount >= 0)
	{
		_nbWithdrawals++;
		std::cout << "withdrawal:" << withdrawal << ";";
		std::cout << "amount:" << _amount << ";";
		std::cout << "nb_withdrawals:" << _nbWithdrawals << std::endl;
		_totalNbWithdrawals++;
		Account::_totalAmount -= withdrawal;
		return (true);
	}
	else
	{
		std::cout << "withdrawal:refused" << ";" << std::endl;
		_amount = p_amount;
		return (false);
	}
}

인덱스; 원금; 회수액; 원금 - 회수액; 회수 횟수; 함수 선언이 boolen으로 되어있고, 원금 - 회수액0보다 클 때, 작을 때의 출력 문구도 다르기 때문에 조건문으로 각 반환 값을 true, false로 나눴다.

Account::~Account()
{
	_displayTimestamp();
	std::cout << " index:" << _accountIndex << ";";
	std::cout << "amount:" << _amount << ";";
	std::cout << "closed" << ";" << std::endl;
}

모든 프로그램을 마무리 하는 함수다. 남은 금액을 출력하면 돼서 생각한대로 출력을 했지만

예시로 받은 log와 출력 값이 달라서 살짝 멘붕이었다. 슬랙과 여러 블로그를 보며 이유를 알 수 있었는데. 간단히 설명하면 시스템 사양이 달라서, 설명을 곁들이자면 맥에서는 vector 안에서의 소멸 순서는 vextor가 구현된 표준 라이브러리에 따라 다르기 때문이다. 까먹지 말고 평가할 때 말해야겠다..

profile
42Seoul -soooh ~ 2022.04

0개의 댓글