1. main()의 실행 결과가 다음과 같도록 Tower 클래스를 작성하라.

mian.cpp

#include <iostream>
#include "Tower.h"
using namespace std;

int main() {
	Tower myTower;
	Tower seoulTower(100);
	cout << "높이는 " << myTower.getHeight() << "미터" << endl;
	cout << "높이는 " << seoulTower.getHeight() << "미터 " << endl;
}

 

 

Tower.h

#ifndef TOWER_H
#define TOWER_H
class Tower {
	int height;
public:
	Tower();
	Tower(int n);
	int getHeight();
};
#endif

 

Tower.cpp

#include <iostream>
#include "Tower.h"
using namespace std;

int main() {
	Tower myTower;
	Tower seoulTower(100);
	cout << "높이는 " << myTower.getHeight() << "미터" << endl;
	cout << "높이는 " << seoulTower.getHeight() << "미터 " << endl;
}


2. 날짜를 다루는 Date 클래스를 작성하고자 한다. Date를 이용하는 main()과 실행 결과는다음과 같다. 클래스 Date를 작성하여 아래 프로그램에 추가하라. 

main.cpp

#include <iostream>
#include "Date.h"
using namespace std;

int main() {
	Date birth(2024, 3, 20);
	Date independenceDay("1945/8/15");
	independenceDay.show();
	cout << birth.getYear() << ',' << birth.getMonth() << ',' << birth.getDay() << endl;
}

 

Date.h

#ifndef DATE_H
#define DATE_H
#include <string>
using namespace std;

class Date {
	int year, month, day;
public:
	Date(int y, int m, int d);
	Date(string date); // string 때문에 include <string>이랑 using namespace std 사용
	int getYear();
	int getMonth();
	int getDay();
	void show();
};
#endif

 

Date.cpp

#include <iostream>
#include <string>
#include "Date.h"

using namespace std;

Date::Date(int y, int m, int d) {
	year = y;
	month = m;
	day = d;
}

Date::Date(string date) {
	int index;
	
	year = stoi(date);
	
	index = date.find('/');
	month = stoi(date.substr(index + 1));

	index = date.find('/');
	day = stoi(date.substr(index + 1));
}

int Date::getYear() {
	return year;
}

int Date::getMonth() {
	return month;
}

int Date::getDay() {
	return day;
}

void Date::show() {
	cout << year << "년" << month << "월" << day << "일" << endl;
}

3.

main.cpp

#include <iostream>
#include "Account.h"
using namespace std;

int main() {
	Account a("kiate", 1, 5000);
	a.deposit(50000);
	cout << a.getOwner() << "의 잔액은 " << a.inquiry() << endl;
	int moeny = a.withdraw(20000);
	cout << a.getOwner() << "의 잔액은 " << a.inquiry() << endl;
}

 

Account.h

#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <string>
using namespace std;

class Account {
	string name;
	int id;
	int balance;
public:
	Account(string n, int i, int b);

	void deposit(int money);
	string getOwner();
	int withdraw(int money);
	int inquiry();
};
#endif

 

Account.cpp

#include <string>
#include "Account.h"

Account::Account(string n, int i, int b) {
	name = n;
	id = i;
	balance = b;
}

void Account::deposit(int money) {
	balance += money;
}

int Account::withdraw(int money) {
	if (balance >= money) {
		balance -= money;
		return money;
	}
	else {
		return 0;
	}
}

string Account::getOwner() {
	return name;
}

int Account::inquiry() {
	return balance;
}

4.

main.cpp

#include <iostream>
#include "CoffeeMachine.h"
using namespace std;

int main() {
	CoffeeMachine java(5, 10, 3);
	java.drinkEspresso();
	java.show();
	java.drinkAmericano();
	java.show();
	java.drinkSugarCoffee();
	java.show();
	java.fill();
	java.show();
}

 

CoffeeMachine.h

#include <iostream>
#include "CoffeeMachine.h"
using namespace std;

int main() {
	CoffeeMachine java(int c, int w, int s);
	java.drinkEspresso();
	java.show();
	java.drinkAmericano();
	java.show();
	java.drinkSugarCoffee();
	java.show();
	java.fill();
	java.show();
}

 

CoffeeMacine.cpp

#include <iostream>
#include "CoffeeMachine.h"
using namespace std;

CoffeeMachine::CoffeeMachine(int c, int w, int s) {
	coffee = c;
	water = w;
	sugar = s;
}

void CoffeeMachine::show() {
	cout << "커피 머신 상태,\t";
	cout << "커피:" << coffee << "\t";
	cout << "물:" << water << "\t";
	cout << "설탕:" << sugar << endl;
}

void CoffeeMachine::drinkEspresso() {
	if (coffee < 1 || water < 1) {
		cout << "재료 부족" << endl;
		return;
	}
	coffee--;
	water--;
}
;
void CoffeeMachine::drinkAmericano() {
	if (coffee < 1 || water < 2) {
		cout << "재료 부족" << endl;
		return;
	}
	coffee--;
	water -= 2;
}
void CoffeeMachine::drinkSugarCoffee() {
	if (coffee < 1 || water < 2 || sugar < 1) {
		cout << "재료 부족" << endl;
		return;
	}
	coffee--;
	water -= 2;
	sugar--;
}
void CoffeeMachine::fill() {
	coffee = water = sugar = 10;
}

5.

 

main.cpp

#include <iostream>
#include "Random.h"
using namespace std;

int main(){
	Random r;
	cout << "-- 0에서 " << RAND_MAX << "까지의 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.next();
		cout << n << ' ';
	}
	cout << endl << endl << "-- 2에서 " << "4까지의 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.nextInRange(2, 4);
		cout << n << ' ';
	}
	cout << endl;
}

 

Random.h

#include <cstdlib>
#include <ctime>
#include "Random.h"

Random::Random() {
	srand((unsigned)time(NULL));
}

int Random::next() {
	return rand();
}

int Random::nextInRange(int a, int b) {
	return a + rand() % (b - a + 1);
}

 

Random.cpp

#include <iostream>
#include "Random.h"
using namespace std;

int main(){
	Random r;
	cout << "-- 0에서 " << RAND_MAX << "까지의 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.next();
		cout << n << ' ';
	}
	cout << endl << endl << "-- 2에서 " << "4까지의 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.nextInRange(2, 4);
		cout << n << ' ';
	}
	cout << endl;
}

6. 

 

main.cpp

#include <iostream>
#include "EvenRandom.h"
using namespace std;

int main()
{
	EvenRandom r;
	cout << "-- 0에서 " << RAND_MAX << "까지의 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.next();
		cout << n << ' ';
	}
	cout << endl << endl << "-- 2에서 " << "4까지의 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.nextInRange(2, 10);
		cout << n << ' ';
	}
	cout << endl;
}

 

EvenRandom.h

#ifndef EVENRANDOM_H
#define EVENRANDOM_H
class EvenRandom {
public:
	EvenRandom();
	int next();
	int nextInRange(int a, int b);
};
#endif

 

EvenRandom.cpp

#include <iostream>
#include "EvenRandom.h"
using namespace std;

int main()
{
	EvenRandom r;
	cout << "-- 0에서 " << RAND_MAX << "까지의 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.next();
		cout << n << ' ';
	}
	cout << endl << endl << "-- 2에서 " << "4까지의 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.nextInRange(2, 10);
		cout << n << ' ';
	}
	cout << endl;
}

7.

 

main.cpp

#include <iostream>
#include "SelectableRandom.h"
using namespace std;

int main()
{
	SelectableRandom r;
	cout << "-- 0에서 " << RAND_MAX << "까지의 짝수 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.next();
		cout << n << ' ';
	}
	cout << endl << endl << "-- 2에서 " << "4까지의 랜덤 홀수 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++)
	{
		int n = r.nextInRange(2, 10);
		cout << n << ' ';
	}
	cout << endl;
}

 

SelectableRandom.h

#ifndef SELECTABLERANDOM_H
#define SELECTABLERANDOM_H
class SelectableRandom {
public:
	SelectableRandom();
	int next();
	int nextInRange(int a, int b);
};
#endif

 

SelectableRandom.cpp

#include <cstdlib>
#include <ctime>
#include "SelectableRandom.h"


SelectableRandom::SelectableRandom() {
	srand((unsigned)time(NULL));
}

int SelectableRandom::next() {
	int n;
	while (true) {
		n = rand();
		if (n % 2 == 0) return n;
	}
}

int SelectableRandom::nextInRange(int a, int b) {
	int n;
	while (true) {
		n =  a + rand() % (b - a + 1);
		if (n % 2 == 1) return n;
	}
}

8.  매개변수 타입이 다른 생성자 

 

main.cpp

#include <iostream>
#include "Integer.h"
using namespace std;

int main()
{
	Integer n(30);
	cout << n.get() << ' ';
	n.set(50);
	cout << n.get() << ' ';

	Integer m("300");
	cout << m.get() << ' ';
	cout << m.isEven();

	cout << endl;
}

 

Integer.h

#ifndef INTEGER_H
#define INTEGER_H
#include <string>
using namespace std;

class Integer {
	int integer;
public:
	Integer(int i) { integer = i; }
	Integer(string i) { integer = stoi(i); }

	int get() { return integer; }
	bool isEven() { return integer % 2 == 0; }
	void set(int i) { integer = i; }
};

#endif

9. 

main.cpp

#include <iostream>
#include "Oval.h"
using namespace std;

int main()
{
	Oval a, b(3, 4);
	a.set(10, 20);
	a.show();
	cout << b.getWidth() << "," << b.getHeight() << endl;
}

 

Oval.h

#ifndef OVAL_H
#define OVAL_H
class Oval {
	int width, height;
public:
	Oval(int w, int h);
	Oval();
	~Oval();
	int getWidth();
	int getHeight();
	void set(int w, int h);
	void show();
};

#endif

 

Oval.cpp

#include <iostream>
#include "Oval.h"
using namespace std;

Oval::Oval(){
	width = height = 1;
}
Oval::Oval(int w, int h) {
	width = w;
	height = h;
}

Oval::~Oval() {
	cout <<"Oval 소멸 : width:" << width << ", height:" << height << endl;
}

int Oval::getHeight() {
	return height;
}

int Oval::getWidth() {
	return width;
}

void Oval::set(int w, int h) {
	width = w;
	height = h;
}

void Oval::show() {
	cout << "타원의 너비:" << width << ", 타원의 높이: " << height << endl;
}

10.

main.cpp

#include <iostream>
#include "Cal.h"
using namespace std;

int main(){
	Add a;
	Sub s;
	Mul m;
	Div d;
	int num1, num2;
	char op;

	while (true) {
		cout << "두 정수와 연산자를 입력하세요>>";
		cin >> num1 >> num2 >> op;
		switch (op) {
		case '+':
			a.setValue(num1, num2);
			cout << a.calculate() << endl;
			break;
		case '-':
			s.setValue(num1, num2);
			cout << s.calculate() << endl;
			break;
		case '*':
			m.setValue(num1, num2);
			cout << m.calculate() << endl;
			break;
		case '/':
			d.setValue(num1, num2);
			cout << d.calculate() << endl;
			break;
		}
	}
}

 

Cal.h

#ifndef Cal_H
#define Cal_h
class Add {
	int a, b;
public:
	void setValue(int x, int y);
	int calculate();
};

class Sub {
	int a, b;
public:
	void setValue(int x, int y);
	int calculate();
};

class Mul {
	int a, b;
public:
	void setValue(int x, int y);
	int calculate();
};

class Div {
	int a, b;
public:
	void setValue(int x, int y);
	int calculate();
};

#endif

 

Cal.cpp

#include "Cal.h"

void Add::setValue(int x, int y) {
	a = x;
	b = y;
}

int Add::calculate() {
	return a + b;
}

void Sub::setValue(int x, int y) {
	a = x;
	b = y;
}

int Sub::calculate() {
	return a - b;
}


void Mul::setValue(int x, int y) {
	a = x;
	b = y;
}

int Mul::calculate() {
	return a * b;
}

void Div::setValue(int x, int y) {
	a = x;
	b = y;
}

int Div::calculate() {
	return a / b;
}

11.

main.cpp

#include <iostream>
#include "Box.h"
using namespace std;

int main(){
	Box b(10, 2);
	b.draw();
	cout << endl;
	b.setSize(7, 4);
	b.setFill('^');
	b.draw();
}

 

Box.h

#ifndef BOX_H
#define BOX_H
class Box {
	int width, height;
	char fill;
public:
	Box(int x, int h);
	void setFill(char f);
	void setSize(int w, int h);
	void draw();
};

#endif

 

Box.cpp

#include <iostream>;
#include "Box.h"
using namespace std;

Box::Box(int w, int h) {
	setSize(w, h); fill = '*';
}

void Box::setFill(char f) {
	fill = f;
}

void Box::setSize(int w, int h) {
	width = w;
	height = h;
}

void Box::draw() {
	for (int n = 0; n < height; n++) {
		for (int m = 0; m < width; m++) cout << fill;
		cout << endl;
	}
}

 

12.

main.cpp

#include <iostream>
#include "Ram.h"
using namespace std;

int main(){
	Ram ram;
	ram.write(100, 20);
	ram.write(101, 30);
	char res = ram.read(100) + ram.read(101);
	ram.write(102, res);
	cout << "102 번지의 값 = " << (int)ram.read(102) << endl;
}

 

Ram.h

#ifndef RAM_H
#define RAM_H
class Ram{
	char mem[100 * 1024];
	int size;
public:
	Ram();
	~Ram();
	char read(int address);
	void write(int address, char value);
};

#endif

 

Ram.cpp

#include <iostream>
#include "Ram.h"
using namespace std;

Ram::Ram() {
	size = 100 * 1024;
	for (int i = 0; i < size; i++) {
		mem[i] = 0;
	}
}

Ram::~Ram() {
	cout << "메모리 제거됨" << endl;
}

void Ram::write(int address, char value) {
	mem[address] = value;
}

char Ram::read(int address) {
	return mem[address];
}

실수의 지수 표현을 클래스 Exp로 작성하라. Exp를 이용하는 main() 함수의 실행 결과는 다음과 같다. 클래스 Exp를 Exp.h 헤더 파일과 Exp.cpp 파일로 분리하여 작성하라.

 

 

Exp.h 

#ifndef Exp_H
#define Exp_H
class Exp {
	int base, exp;
public:
	Exp();
	Exp(int a);
	Exp(int a, int b);
	int getValue();
	int getExp();
	int getBase();
	bool equals(Exp b);
};
#endif

 

Exp.cpp

#include "Exp.h"

Exp::Exp() {
	base = exp = 1;
}

Exp::Exp(int a) {
	base = a;
	exp = 1;
}

Exp::Exp(int a, int b) {
	base = a;
	exp = b;
}

int Exp::getBase() {
	return base;
}

int Exp::getExp() {
	return exp;
}

int Exp::getValue() {
	int result = 1;
	for (int i = 0; i < exp; i++) {
		result *= base;
	}
	return result;
}

bool Exp::equals(Exp b) {
	return getValue() == b.getValue(); 
}

 

main.cpp

#include <iostream>
using namespace std;
#include "Exp.h"

int main() {
	Exp a(3, 2);
	Exp b(9);
	Exp c;

	cout << a.getValue() << ' ' << b.getValue() << ' ' << c.getValue() << endl;
	cout << "a의 베이스 " << a.getBase() << ',' << "지수 " << a.getExp() << endl;

	if (a.equals(b))
		cout << "same" << endl;
	else
		cout << "not same" << endl;
}

1. 다음은 색의 3요소인 red,green, blue로 색을 추상화한 Color 클래스를 선언하고 활용하는 코드이다. 빈칸을 채워라. red, green, blue는 0~255의 값만 가진다.

#include <iostream>
using namespace std;

class Color {
	int red, green, blue;
public:
	Color() { red = green = blue = 0; }
	Color(int r, int g, int b) { red = r; green = g; blue = b; }
	void setColor(int r, int g, int b) { red = r; green = g; blue = b; }
	void show() { cout << red << ' ' << green << ' ' << blue << endl; }
};

int main() {
	Color screenColor(255, 0, 0);
	Color* p;
	p = &screenColor;
	p->show(); // cout << p->show() (X)
	Color colors[3];
	p = colors;

	p[0].setColor(255, 0, 0);
	p[1].setColor(0, 255, 0);
	p[2].setColor(0, 0, 255);

	for (int i = 0; i < 3; i++) {
		p[i].show();
	}
}

2. 정수 공간 5개를 배열로 동적 할당받고, 정수를 5개 입력받아 평균을 구하고 출력한 뒤 배열을 소멸시키도록 main() 함수를 작성하라.

#include <iostream>
using namespace std;

int main() {
	int* p = new int[5];
	int sum = 0;
	
	cout << "정수 5개 입력>>";
	for (int i = 0; i < 5; i++) {
		cin >> p[i];
	}

	for (int i = 0; i < 5; i++) {
		sum += p[i];
	}
	
	cout << "평균 " << (float)sum / 5 << endl;
	
	delete[] p;

}

3. string 클래스를 이용하여 빈칸을 포함하는 문자열을 입력받고 문자열에서 'a'가 몇개 있는지 출력하는 프로그램을 작성해보자.

 

(1) 문자열에서 'a'를 찾기 위해  string 클래스의 멤버 at()나 []를 이용하여 작성하라.

#include <iostream>
#include <string>
using namespace std;

int main() {
	string s;
	int count = 0;

	cout << "문자열 입력>>";
	getline(cin, s, '\n');

	for (int i = 0; i < s.length(); i++) { // s.length() 대신 s.size() 가능
		if (s[i] == 'a') // s[i] 대신 s.at(i) 가능
			count++;
	}

	cout << "문자 a는 " << count << "개 있습니다." << endl;

}

 

(2) 문자열에서 'a'를 찾기 위해 string 클래스의 find() 멤버 함수를 이용하여 작성하라. text.find('a',index);는 text 문자열의 index 위치부터 'a'를 찾아 문자열 내 인덱스를 리턴한다.

#include <iostream>
#include <string>
using namespace std;

int main() {
	string s;
	int count = 0;
	int index = 0;

	getline(cin, s);
	while (true) {
		index = s.find('a', index);
		if (index == -1) break;
		index += 1;
		count++;
	}

	cout << "문자 a는 " << count << "개 있습니다." << endl;

}
#include <iostream>
#include <string>
using namespace std;

int main() {
	string s;
	int count = 0, index = 0;

	cout << "문자열 입력>>";
	getline(cin, s, '\n');
	
	index = s.find('a');
	while (index != -1) {
		count++;
		index = s.find('a', index + 1);
	}

	cout << "문자 a는 " << count << "개 있습니다." << endl;

}

4.

 

다음과 같은 Sample 클래스가 있다.

class Sample {
	int* p;
	int size;
public:
	Sample(int n) {
		size = n;
		p = new int[n];
	}
	void read();
	void write();
	int big();
	~Sample();
};

 

다음 main() 함수가 실행되도록 Sample 클래스를 완성하라.

int main() {
	Sample s(10);
	s.read();
	s.write();
	cout << "가장 큰 수는 " << s.big() << endl;
}

 

 

void Sample::read() {
	for (int i = 0; i < size; i++) {
		cin >> p[i];
	}
}

void Sample::write() {
	for (int i = 0; i < size; i++) {
		cout << p[i] << ' ';
	}
	cout << endl;
}

int Sample::big() {
	int max = p[0];
	for (int i = 1; i < size; i++) {
		if (max < p[i])
			max = p[i];
	}
	return max;
}

Sample::~Sample() {
	delete[] p;
}

 

 

전체 코드 

#include <iostream>
#include <string>
using namespace std;

class Sample {
	int* p;
	int size;
public:
	Sample(int n) {
		size = n;
		p = new int[n];
	}
	void read();
	void write();
	int big();
	~Sample();
};

void Sample::read() {
	for (int i = 0; i < size; i++) {
		cin >> p[i];
	}
}

void Sample::write() {
	for (int i = 0; i < size; i++) {
		cout << p[i] << ' ';
	}
	cout << endl;
}

int Sample::big() {
	int max = p[0];
	for (int i = 1; i < size; i++) {
		if (max < p[i])
			max = p[i];
	}
	return max;
}

Sample::~Sample() {
	delete[] p;
}

int main() {
	Sample s(10);
	s.read();
	s.write();
	cout << "가장 큰 수는 " << s.big() << endl;
}

5. string 클래스를 이용하여 사용자가 입력한 영문 한 줄을 입력받고 글자 하나만 랜덤하게 수정하여 출력하는 프로그램을 작성하라. 

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

int main() {
	srand((unsigned)time(NULL));
	string s;
	int index;
	cout << "아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)" << endl;
	while (true) {
		cout << ">>";
		getline(cin, s, '\n');
		if (s.compare("exit") == 0) // s == "exit" 도 가능 
			break;

		index = rand() % s.length();
		cout << s[index] << endl;
	}

}

6. string 클래스를 이용하여 사용자가 입력한 영문 한 줄을 문자열로입력받고 거꾸로 출력하는 프로그램을 작성하라.

#include <iostream>
#include <string>
using namespace std;

int main() {
	string s;
	cout << "아래에 한줄을 입력하세요.(exit를 입력하면 종료합니다.)" << endl;
	while (true) {
		cout << ">>";
		getline(cin, s, '\n');
		if (s == "exit") break;

		for (int i = (s.length() - 1); i >= 0; i--) {
			cout << s[i];
		}
        
		cout << endl;
	}
}
#include <iostream>
#include <string>
using namespace std;

int main() {
	string text;
	cout << "아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)" << endl;
	while(true) {
		cout << ">>";
		getline(cin, text, '\n');
		if(text == "exit")
			break;
		int size = text.length();
		int n = size/2;
		for(int i=0; i<n; i++) {
			char tmp = text[i];
			text[i] = text[size-i-1];
			text[size-i-1] = tmp;
		}
		cout << text << endl;
	}
}

7. 다음과 같이 원을 추상화한 Circle 클래스가 있다. Circle 클래스와 main() 함수를 작성하고 3개의 Circle 객체를 가진 배열을 선언하고, 반지름 값을 입력받고 면적이 100보다 큰 원의 개수를 출력하는 프로그램을 완성하라. Circle 클래스도 완성하라.

class Circle {
	int radius;
public:
	void setRadius(int radius);
	double getArea();
};

#include <iostream>
#include <string>
using namespace std;

class Circle {
	int radius;
public:
	void setRadius(int radius);
	double getArea();
};

void Circle::setRadius(int radius) {
	this->radius = radius;
}

double Circle::getArea() {
	return 3.14 * radius * radius;
}

int main() {
	Circle arr[3];
	int radius, count = 0;

	for (int i = 0; i < 3; i++) {
		cout << "원 " << i+1 << "의 반지름 >> ";
		cin >> radius;
		arr[i].setRadius(radius);
	}

	for (int i = 0; i < 3; i++) {
		if (arr[i].getArea() > 100)
			count++;
	}
	
	cout << "면적이 100보다 큰 원은 " << count << "개 입니다." << endl;

}

8. 실습 문제 7의 문제를 수정해보자. 사용자로부터 다음과 같이 원의 개수를 입력바독, 원의 개수만큼 반지름을 입력받는 방식으로 수정하라. 원의 개수에 따라 동적으로 배열을 할당받아야 한다.

#include <iostream>
#include <string>
using namespace std;

class Circle {
	int radius;
public:
	void setRadius(int radius);
	double getArea();
};

void Circle::setRadius(int radius) {
	this->radius = radius;
}

double Circle::getArea() {
	return 3.14 * radius * radius;
}

int main() {
	Circle* p;
	int radius, count = 0, n;

	cout << "원의 개수 >> ";
	cin >> n;
	p = new Circle[n];

	for (int i = 0; i < n; i++) {
		cout << "원 " << i+1 << "의 반지름 >> ";
		cin >> radius;
		p[i].setRadius(radius);
	}

	for (int i = 0; i < n; i++) {
		if (p[i].getArea() > 100)
			count++;
	}
	
	cout << "면적이 100보다 큰 원은 " << count << "개 입니다." << endl;

}

9. 다음과 같은 Person 클래스가 있다. Person 클래스와 main() 함수를 작성하여, 3개의 Person 객체를 가지는 배열을 선언하고, 다음과 같이 키보드에서 이름과 전화번호를 입력받아 출력하고 검색하는 프로그램을 완성하라.

class Person {
	string name;
	string tel;
public:
	Person();
	string getName() { return name; }
	string getTel() { return tel; }
	void set(string name, string tel);
};

 

#include <iostream>
#include <string>
using namespace std;

class Person {
	string name;
	string tel;
public:
	Person();
	string getName() { return name; }
	string getTel() { return tel; }
	void set(string name, string tel);
};

Person::Person() {

}

void Person::set(string name, string tel) {
	this->name = name;
	this->tel = tel;
}


int main() {
	Person arr[3];
	string name, tel;

	cout << "이름과 전화 번호를 입력해 주세요" << endl;
	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
		cout << "사람 " << i + 1 << ">> ";
		cin >> name >> tel;
		arr[i].set(name, tel);
	}
	cout << "모든 사람의 이름은 ";
	for (int i = 0; i < 3; i++) {
		cout << arr[i].getName() << ' ';
	}
	cout << endl;
	cout << "전화번호 검색합니다. 이름을 입력하세요>>";
	cin >> name;

	for (int i = 0; i < 3; i++) {
		if (name == arr[i].getName()) {
			cout << "전화번호는 " << arr[i].getTel() << endl;
			break;
		}
	}
}

10. 다음에서 Person은 사람을, Family는 가족을 추상화한 클래스로서 완성되지 않은클래스이다.

 다음에서 Person은 사람을, Family는 가족을 추상화한 클래스로서 완성되지 않은 클래스이다.

class Person {
	string name;
public:
	Person(string name) { this->name = name; }
	string getName() { return name; }
};

class Family {
	Person* p;
	int size;
public:
	Family(string name, int size);
	void show();
	~Family();
};

 

다음 main()이 작동하도록 Person과 Family 클래스에필요한 멤버들을 추가하고 코드를 완성하라.

int main() {
	Family* simpson = new Family("Simson", 3);
	simpson->setName(0, "Mr. Simpson");
	simpson->setName(1, "Mrs. Simpson");
	simpson->setName(2, "Bart Simpson");
	simpson->show();
	delete simpson;
}

 

#include <iostream>
#include <string>
using namespace std;

class Person {
	string name;
public:
	Person(){}
	Person(string name) { this->name = name; }
	string getName() { return name; }
	void setName(string name);
};

class Family {
	Person* p;
	int size;
	string name;
public:
	Family(string name, int size);
	void show();
	void setName(int index, string name);
	~Family();
};


void Person::setName(string name) {
	this->name = name;
}

Family::Family(string name, int size) {
	this->name = name;
	this->size = size;
	p = new Person[size];
}

void Family::show() {
	cout << name << "가족은 다음과 같이" << size << "명 입니다." << endl;
	for (int i = 0; i < size; i++) {
		cout << p[i].getName() << '\t';
	}
}

void Family::setName(int index, string name) {
	p[index].setName(name);
}

Family::~Family() {
	delete[] p;
}


int main() {
	Family* simpson = new Family("Simson", 3);
	simpson->setName(0, "Mr. Simpson");
	simpson->setName(1, "Mrs. Simpson");
	simpson->setName(2, "Bart Simpson");
	simpson->show();
	delete simpson;
}

11. 다음은 커피자판기로 작동하는 프로그램을 만들기 위해 필요한 두 클래스이다.

class Container {
	int size;
public:
	Container() { size = 10; }
	void fill();
	void consume();
	int getSize();
};

class CoffeeVendingMachine {
	Container tong[3];
	void fill();
	void selectEspresso();
	void selectAmericano();
	void seletSugarCoffee();
	void show();
public:
	void run();
};

 

 

다음과 같이 실행되도록 amin() 함수와 CoffeeVendingMachine, Container를 완성하라. 만일 커피, 물, 설탕 중 잔량이 하나라도 부족해 커피를 제공할 수 없는 경우 '원료가 부족합니다.'를 출력하라.

#include <iostream>
using namespace std;



void Container::fill() {
	size = 10;
}
void Container::consume() {
	size -= 1;
}
int Container::getSize() {
	return size;
}

void CoffeeVendingMachine::fill() {
	for (int i = 0; i < 3; i++) {
		tong[i].fill();
	}
	show();
}

void CoffeeVendingMachine::selectEspresso() {
	if (tong[0].getSize() < 1 || tong[1].getSize() < 1) {
		cout << "원료가 부족합니다." << endl;
		return;
	}
	tong[0].consume();
	tong[1].consume();
	cout << "에스프레소 드세요" << endl;
}

void CoffeeVendingMachine::selectAmericano() {
	if (tong[0].getSize() < 1 || tong[1].getSize() < 2) {
		cout << "원료가 부족합니다." << endl;
		return;
	}
	tong[0].consume();
	tong[1].consume();
	tong[1].consume();
	cout << "아메리카노 드세요" << endl;
}

void CoffeeVendingMachine::seletSugarCoffee() {
	if (tong[0].getSize() < 1 || tong[1].getSize() < 2 || tong[2].getSize() < 1) {
		cout << "원료가 부족합니다."<< endl;
		return;
	}
	tong[0].consume();
	tong[1].consume();
	tong[1].consume();
	tong[2].consume();
	cout << "설탕커피 드세요" << endl;
}

void CoffeeVendingMachine::show() {
	cout << "커피 " << tong[0].getSize() << ", 물 " << tong[1].getSize() << ", 설탕 " << tong[2].getSize() << endl;
}

void CoffeeVendingMachine::run() {
	int sel;
	cout << "***** 커피자판기를 작동합니다. *****" << endl;
	while (true) {
		cout << "메뉴를 눌러주세요(1:에스프레소, 2:아메리카노, 3: 설탕커피, 4:잔량보기, 5:채우기)>> ";
		cin >> sel;
		switch (sel) {
		case 1:
			selectEspresso();
			break;
		case 2:
			selectAmericano();
			break;
		case 3:
			seletSugarCoffee();
			break;
		case 4:
			show();
			break;
		case 5:
			fill();
			break;
		default: 
			cout << "메뉴에 없는 번호입니다. 다시 눌러주세요" << endl;
			continue;
		}
	}
}

int main() {
	CoffeeVendingMachine C;
	C.run();
}

 

 

01. cout과 << 연산자를 이용하여, 1에서 100까지 정수를 다음과 같이 한 줄에 10개씩 출력하라. 각 정수는 탭으로 분리하여 출력하라.

#include <iostream>
#include <string>
using namespace std;

int main() {
	for (int i = 1; i <= 100; i++) {
		cout << i << '\t';
		if ((i % 10) == 0)
			cout << endl;
	}
}

02. cout과 << 연산자를 이용하여 다음과 같이 구구단을 출력하는 프로그램을 작성하라.

#include <iostream>
#include <string>
using namespace std;

int main() {
	for (int i = 1; i <= 9; i++) {
		for (int j = 1; j <= 9; j++) {
			cout << j << 'x' << i << '=' << i * j << '\t';
		}
		cout << endl;
	}
}

 


03. 키보드로부터 두개의 정수를 읽어 큰 수를 화면에 출력하라.

 

 

#include <iostream>
using namespace std;

int main() {
	int num1, num2;
	cout << "두 수를 입력하라>>";
	cin >> num1 >> num2;
	cout << "큰 수 = "<< ((num1 > num2) ? num1 : num2); 
	// () 괄호 없이 (num1 > num2) ? num1 : num2 일 경우 true 또는 false가 반환되어 1 또는 0이 출력됨 
	// 연산자 우선순위 때문
}
#include <iostream>
using namespace std;

int main() {
	int a, b;
	cout << "두 수를 입력하라>>";
	cin >> a >> b;
	(a > b) ? (cout << a) : (cout << b);

}

04. 소수점을 가지는 5개의 실수를 입력 받아 제일 큰 수를 화면에 출력하라.

#include <iostream>
using namespace std;

float find_max(float num[], int size) {
	float max = num[0];
	for (int i = 1; i < size; i++) {
		if (max < num[i])
			max = num[i];
	}
	return max;
}

int main() {
	float num[5], max;
	int size = sizeof(num) / sizeof(num[0]);

	cout << "5 개의 실수를 입력하라>>";
	for (int i = 0; i < size; i++)
		cin >> num[i];

	max = find_max(num, size);
	cout << "제일 큰 수 = " << max;
}

05. <Enter> 키가 입력될 때까지 문자들을 읽고, 입력된 문자 'x'의 개수를 화면에 출력하라.

 

#include <iostream>
using namespace std;

int count_x(char str[]) {
	int count = 0;
	for (int i = 0; str[i] != '\0'; i++) {
		if (str[i] == 'x')
			count++;
	}
	return count;
}

int main() {
	char str[100];
	int count;

	cout << "문자들을 입력하라(100개 미만).\n";
	cin.getline(str, sizeof(str));
	
	count = count_x(str);
	cout << "x의 개수는 " << count;
}

06. 문자열 두 개 입력받고 두 개의 문자열이 같은지 검사하는 프로그램을 작성하라. 만일 같으면 "같습니다", 아니면 "같지않습니다."를 출력하라.

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int is_Same(char* pass, char* re_pass) {
	if (strcmp(pass, re_pass) == 0)
		return 1;
	return 0;
}

int main() {
	char pass[10], re_pass[10];

	cout << "새 암호를 입력하세요>>";
	cin >> pass;
	cout << "새 암호를 다시 한 번 입력하세요>>";
	cin >> re_pass;

	if (is_Same(pass, re_pass))
		cout << "같습니다.\n";
	else
		cout << "다릅니다.\n";
}

 

책에 적힌 해당 문제에 대한 목적은 위의 방법이지만 사용자가 어느 길이의 암호를 입력할지 정해져 있지 않다면 아래 방법(string)이 더 적합하다고 생각한다.

#include <iostream>
#include <string>
using namespace std;

int isSame(string s1, string s2) {
	if (s1 == s2)
		return 1;
	return 0;
}

int main() {
	string pass, re_pass;

	cout << "새 암호를 입력하세요>>";
	getline(cin, pass);
	cout << "새 암호를 다시 한 번 입력하세요>>";
	getline(cin, re_pass);
	if (isSame(pass, re_pass))
		cout << "같습니다\n";
	else
		cout << "다릅니다\n";

}

 


07. 다음과 같이 "yes"가 입력될 때까지 종료하지 않는 프로글매을 작성하라. 사용자로부터의 입력은 cin.getline() 함수를 사용하라.

#include <iostream>
#include <string>
#include <cstring>
//using namespace std;

int is_end(char *s) {
	if (strcmp(s,"yes")==0)
		return 0;
	return 1;
}

int main() {
	char ans[100];
	int result;

	do {
		std::cout << "종료하고싶으면 yes를 입력하세요>>";
		std::cin.getline(ans, sizeof(ans), '\n');
	} while (is_end(ans));
	// while(true) { if (strcmp() == 0) break; } 도 가능하다
    
    
	std::cout << "종료합니다...";

}

 

책에서 cin.getline()을 사용하라 하였지만

사용자가 어느 길이 만큼의 문자열을 입력할지 모르는 상황에서는 string과 std::getline()을 사용하는게 더 적합하다고 생각한다. 

#include <iostream>
#include <string>
//using namespace std;

int is_end(std::string s) {
	if (s == "yes")
		return 0;
	return 1;
}

int main() {
	std::string ans;
	int result;

	do {
		std::cout << "종료하고싶으면 yes를 입력하세요>>";
		getline(std::cin, ans,'\n');
	} while (is_end(ans));
	
	std::cout << "종료합니다...";

}

08. 한 라인에 ';' 으로 5개의 이름을 구분하여 입력받아, 각 이름을 끊어내어 화면에 출력하고 가장 긴 이름을 판별하라.

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

#define ROWS 5
#define COLS 100

char* find_long(char arr[][COLS]) {
	char* max = arr[0];
	for (int i = 1; i < ROWS; i++) {
		if (strlen(max) < strlen(arr[i]))
			max = arr[i];
	}
	return max;
}

void print_name(char arr[][COLS]) {
	for (int i = 0; i < ROWS; i++) {
		cout << i + 1 << " : " << arr[i] << endl;
	}
}

int main() {
	char name[5][100];
	char* longest;

	cout << ROWS << " 명의 이름을 ';'으로 구분하여 입력하세요" << endl;
	cout << ">>";

	for (int i = 0; i < ROWS; i++) {
		cin.getline(name[i], COLS, ';');
	}

	print_name(name);
	longest = find_long(name);
	cout << "가장 긴 이름은 " << longest << endl;

}

09. 이름, 주소, 나이를 입력받아 다시 출력하는 프로그램을 작성하라. 실행 예시는 다음과 같다.

#include <iostream>
#include <string>
using namespace std;

int main() {
	int age;
	char name[20];
	string address;

	cout << "이름은?";
	cin.getline(name, sizeof(name), '\n');
	cout << "주소는?";
	getline(cin, address, '\n');
	cout << "나이는?";
	cin >> age;
	cout << age << ", " << address << ", " << age << "세" << endl;
}

10. 문자열을 하나 입력받고 문자열의 부분 문자열을 다음과 같이 출력하는 프로그램을 작성하라. 예시는 다음과 같다.

#include <iostream>
#include <string>
using namespace std;

int main() {
	string str;
	cout << "문자열 입력>>";
	getline(cin, str);
	for (int i = 0; str[i] != '\0'; i++) {
		for (int j = 0; j <= i; j++) {
			cout << str[j];
		}
		cout << endl;
	}
}

11. 다음 C 프로그램을 C++ 프로그램으로 수정하여 실행하라.

#include <stdio.h>

int main() {
	int k, n = 0;
	int sum = 0;

	printf("끝 수를 입력하세요>>");
	scanf("%d", &n);
	for (k = 1; k <= n; k++) {
		sum += k;
	}
	printf("1에서 %d까지의 합은 %d 입니다. \n", n, sum);
	return 0;
}

#include <iostream>
using namespace std;

int main() {
	int k, n = 0;
	int sum = 0;
	cout << "끝 수를 입력하세요>>";
	cin >> n;
	for (k = 1; k <= n; k++) {
		sum += k;
	}
	cout << "1에서 " << n << "까지의 합은 " << sum << "입니다." << endl;

}

 

여기서는 반복문을 통해 합을 구했지만 등차수열의 합을 이용하는 것이 훨씬 효과적이다. ( 평균  * 항의 갯수)


12. 다음 C 프로그램을 C++ 프로그램으로 수정하여 실행하라. 이 프로그램의 실행 결과는 연습문제 11과 같다.

#include <iostream>
using namespace std;

int sum(int, int);

int main() {
	int n = 0;
	cout << "끝 수를 입력하세요>>";
	cin >> n;
	cout << "1에서 " << n << "까지의 합은 " << sum(1,n) << "입니다." << endl;
}

int sum(int a, int b) {
	int k, res = 0;
	for (k = a; k <= b; k++) {
		res += k;
	}
	return res;
}

13. 중식당의 주문 과정을 C++ 프로그램으로 작성해보자. 다음 실행 결과와 같이 메뉴와 사람 수를 입력받고 이를 출력하면 된다. 잘못된 입력을 가려내는 부분도 코드에 추가하라.

방법 1) 

#include <iostream>
using namespace std;

int main() {
	int menu, people;
	cout << "***** 승리장에 오신 것을 환영합니다. *****\n";
	
	while (true) {
		cout << "짬뽕:1, 짜장:2, 군만두:3, 종료:4>>\t";
		cin >> menu;
		if (menu > 4 || menu < 1) {
			cout << "다시 주분하세요!!\n";
			continue;
		}
		else if (menu == 4) {
			cout << "오늘 영업은 끝났습니다.\n";
			break;
		}

		cout << "몇인분?";
		cin >> people;

		switch (menu) {
		case 1:
			cout << "짬뽕 " << people << "인분 나왔습니다" << endl;
			break;
		case 2:
			cout << "짜장 " << people << "인분 나왔습니다" << endl;
			break;
		case 3:
			cout << "군만두 " << people << "인분 나왔습니다" << endl;
			break;
		}
	}
}

 

방법2) 

 c++ 에서 bool타입을 지원하면서 기존에 리턴타입 int 함수(리턴값이 1/0)  대신 bool 타입으로도 대체 가능해짐 

어떤 방식이 더 효율적일까.. 

#include <iostream>
using namespace std;

string menu_arr[] = { "짬뽕","짜장","군만두", "종료"};
#define SIZE 4

void print_menu() {
	for (int i = 0; i < SIZE; i++) {
		cout << menu_arr[i] << ":" << i + 1;
		if (i < SIZE - 1)
			cout << ", ";
	}
	cout << ">>\t";
}

bool check_menu(int menu) {
	return menu >= 1 && menu <= SIZE;
}

bool is_end(int menu) {
	return menu == SIZE;
}

void print_order(int menu, int people) {
	cout << menu_arr[menu - 1] << " " << people << "인분 나왔습니다.\n";
}


int main() {
	int menu, people;
	cout << "***** 승리장에 오신 것을 환영합니다. *****"<< endl;
	while (true) {
		print_menu();
		cin >> menu;
		if (!check_menu(menu)) {
			cout << "다시 주문하세요!!" << endl;
			continue;
		}
		if (is_end(menu)) {
			cout << "오늘 영업은 끝났습니다." << endl;
			break;
		}
		cout << "몇인분?";
		cin >> people;
		print_order(menu, people);
	}
}

14. 커피를 주문하는 간단한 C++ 프로그램을 작성해보자. 커피 종류는 "에스프레소", "아메리카노", "카푸치노"의 3가지이며 가격은 각각 2000원, 2300원, 2500원이다. 하루에 20000원 이상 벌게 되면 카페를 닫는다. 실행 결과와 같이 작돋하는 프로그램을 작성하라.

#include <iostream>
#include <cstring>
using namespace std;

int main() {
	char coffee[100];
	int money = 0, num, price;
	cout << "에스프레소 2000원, 아메리카노 2300원, 카푸치노 2500원입니다.\n";

	while (money < 20000) {
		
		cout << "주문 >> ";
		cin >> coffee >> num;

		if (num < 0) {
			cout << "잘못된 수량입니다. 다시 입력해주세요\n";
			continue;
		}

		else if (strcmp(coffee, "에스프레소") == 0)
			price = num * 2000;
		else if (strcmp(coffee, "아메리카노") == 0)
			price = num * 2300;
		else if (strcmp(coffee, "카푸치노") == 0)
			price = num * 2500;
		else {
			cout << "다시 메뉴를 선택해주세요" << endl;
			continue;
		}

		money += price;
		cout << price << "원입니다. 맛있게 드세요\n";
	}
	cout << "오늘 " << money << "원을 판매하여 카페를 닫습니다. 내일 봐요~~\n";
}

15. 덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/), 나머지(%)의 정수 5칙 연산을 할 수 있는 프로그램을 작성하라. 식은 다음과 같은 형식으로 입력된다. 정수와 연산자는 하나의 빈칸으로 분리된다. ( cin 으로 입력 받을 때, 데이터의 유형은 입력 받는 변수의 데이터타입에 따라 달라진다)

1) 책에서 권장하는 방식

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main() {
	int num1, num2;
	char cal[10], op;
	char* tok[3];

	while (true) {
		cout << "?";
		cin.getline(cal, 10);

		tok[0] = strtok(cal, " ");
		tok[1] = strtok(NULL, " ");
		tok[2] = strtok(NULL, " ");

		num1 = atoi(tok[0]);
		num2 = atoi(tok[2]);

		switch (*tok[1]) {
		case '+':
			cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
			break;
		case '-':
			cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
			break;
		case '*':
			cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
			break;
		case '/':
			cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
			break;
		case '%':
			cout << num1 << " % " << num2 << " = " << num1 % num2 << endl;
			break;

		default:
			cout << "잘못된 수식을 입력했습니다.\n";
			continue;
		}
	}
}

 

2) 내 맘대로 작성한 코드

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main() {
	int num1, num2;
	char op;

	while (true) {
		cout << "?";
		cin >> num1 >> op >> num2;

		switch (op) {
		case '+':
			cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
			break;
		case '-':
			cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
			break;
		case '*':
			cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
			break;
		case '/':
			cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
			break;
		case '%':
			cout << num1 << " % " << num2 << " = " << num1 % num2 << endl;
			break;

		default:
			cout << "잘못된 수식을 입력했습니다.\n";
			continue;
		}
	}
}

16. 영문 텍스트를 입력받아 알파벳 히스토그램을 그리는 프로그램을 작성하라. 대문자는 모두 소문자로 집계하며, 텍스트 입력의 끝은 ';' 문자로 한다. 

 

#include <iostream>
#include <cstring>
using namespace std;

int main() {
	char input[10001];
	int alpha[26] = { 0 };
	int total = 0;

	cout << "영문 텍스트를 입력하세요. 히스토그램을 그립니다." << endl;
	cout << "텍스트의 끝은 ; 입니다. 10000개까지 가능합니다." << endl;
	cin.getline(input, sizeof(input), ';');
	
	for (int i = 0; input[i] != '\0'; i++) {
		if (isalpha(input[i])) {
			total++;
			alpha[tolower(input[i]) - 'a']++;
		}
	}

	cout << "총 알파벳 수 " << total << "\n\n";

	for (char i = 'a'; i <= 'z'; i++) {
		cout << i << " (" << alpha[(int)i - 'a'] << ")\t:";
		for (int j = 0; j < alpha[(int)i - 'a']; j++)
			cout << "*";
		cout << endl;
	}
}

두 사람이 하는 가위, 바위, 보 게임을 만들어보자 두 사람의 이름은 '로미오'와 '줄리엣'으로 한다. 먼저 "로미오>>"를 출력하고 '로미오'로부터 "가위", "바위", "보" 중 하나의 문자열을 입력받고, 다시 "줄리엣>>"을 출력하고 '줄리엣'으로부터 "가위", "바위", "보" 중 하나의 문자열을 입력받는다. 누가 이겼는지 판단하여 승자를 출력한다. 비기게 되면 "비겼습니다."라고 출력하고 프로그램을 종료한다. 

#include <iostream>
#include <string>
using namespace std;

int main() {
	string ro, jul;
	cout << "가위 바위 보 게임을 합니다. 가위, 바위, 보 중에서 입력하세요.\n";
	cout << "로미오>>";
	getline(cin, ro);
	cout << "줄리엣>>";
	getline(cin, jul);

	if ((ro == "가위" && jul == "보") || (ro == "바위" && jul == "가위") || (ro == "보" && jul == "바위"))
		cout << "로미오가 이겼습니다." << endl;
	else if (ro == jul)
		cout << "로미오와 줄리엣이 비겼습니다." << endl;
	else
		cout << "줄리엣이 이겼습니다." << endl;
}

 

코드를 작성하고 나니 좀 많이 아쉬운 점이 있다.

가위, 바위, 보가 숫자로 0,1,2 일 경우 입력받은 하나의 값에서 1을 더하고 3의 나머지를 구함으로써 승패 여부를 간단하게 할 수 있는데 위의 지저분한 논리식이 마음에 들지 않았다 

그래서 이를 고려하여 다시 코드를 작성하였다.

 

배열을 사용하여 코드의 반복은 간소화하고 위의 논리식을 간소화 하였다 

#include <iostream>
#include <string>
using namespace std;

struct user {
	char name[7];
	string in;
	int in_n;
};


int main() {
	struct user u[2] = { {"로미오"}, {"줄리엣"} };
	string rjb[] = { "가위", "바위", "보" };
	int i, j;

	cout << "가위 바위 보 게임을 합니다. 가위, 바위, 보 중에서 입력하세요.\n";
	for (i = 0; i < sizeof(u) / sizeof(struct user); i++) {
		cout << u[i].name << ">>";
		getline(cin, u[i].in);

		for (j = 0; j < sizeof(rjb) / sizeof(rjb[0]); j++) {
			if (u[i].in == rjb[j]) {
				u[i].in_n = j;
				break;
			}
		}
		if (j == sizeof(rjb) / sizeof(rjb[0])) {
			cout << "입력된 값이 유효하지 않습니다.\n";
			return -1;
		}
	}
	if ((u[0].in_n + 1) % 3 == u[1].in_n)
		cout << u[1].name << "가 이겼습니다." << endl;

	else if (u[0].in_n == u[1].in_n)
		cout << u[0].name << "과 " << u[1].name << "이 비겼습니다. \n";

	else
		cout << u[0].name << "이 이겼습니다." << endl;

}

 c언어에서처럼 char *rjb[] = {"가위", "바위", "보"}; 했더니 에러가 났다, c++은 이 방식이 불가하고 대신 string 배열을 대신 사용한다.

이전 코드보다 확장성, 유지보수성, 안정성이 높아졌다. 

해당 코드를 chatgpt에 넣어보고 더 개선할점을 요구했다. 

 

#include <iostream>
#include <string>
using namespace std;

struct user {
    string name;
    string in;
    int in_n;
};

constexpr int RJB_COUNT = 3;
const string rjb[RJB_COUNT] = { "가위", "바위", "보" };

int getInputIndex(const string& input, const string rjb[], int size) {
    for (int i = 0; i < size; i++) {
        if (input == rjb[i]) return i;
    }
    return -1; // 유효하지 않은 입력
}

int determineWinner(int p1, int p2) {
    if ((p1 + 1) % 3 == p2) return 2; // 플레이어 2 승리
    if (p1 == p2) return 0;           // 무승부
    return 1;                         // 플레이어 1 승리
}

int main() {
    user u[2] = { {"로미오"}, {"줄리엣"} };
    int result;

    cout << "가위 바위 보 게임을 합니다. 가위, 바위, 보 중에서 입력하세요.\n";

    for (int i = 0; i < 2; i++) {
        while (true) {
            cout << u[i].name << ">> ";
            getline(cin, u[i].in);

            u[i].in_n = getInputIndex(u[i].in, rjb, RJB_COUNT);
            if (u[i].in_n != -1) break;

            cout << "입력된 값이 유효하지 않습니다. 다시 입력해주세요.\n";
        }
    }

    result = determineWinner(u[0].in_n, u[1].in_n);
    if (result == 1)
        cout << u[0].name << "이 이겼습니다." << endl;
    else if (result == 2)
        cout << u[1].name << "가 이겼습니다." << endl;
    else
        cout << u[0].name << "과 " << u[1].name << "이 비겼습니다." << endl;

    return 0;
}

이렇게 개선해줬다. 확실히 이 코드가 더 좋아보인다. 

 

1. 빌드 프로세스 

프로그래밍 언어: 고수준의 소스 코드 작성에 사용, Human-readable

오브젝트 코드: Machin-readable, 컴퓨터가 실행할 수 있는 코드

컴파일러: 소스코드를 오브젝트 코드로 변환하는 도구

링커: 오브젝트 코드를 실행 파일(exe)로 변환하는 도구

테스트 & 디버깅: 프로그램에 존재하는 오류를 찾고, 수정하는 과정

 

IDE(Integrated Development Environment)

텍스트 에디터 + 컴파일러 + 링커 + (디버거)

텍스트 에디터: .cpp 소스 코드 / .h 헤더 파일의 편집기

C++ Build Process

 

비주얼 스튜디오 기준

컴파일 ( Ctrl + F7)

빌드/Compil + Linking  (프로젝트 우클릭 후 빌드 클릭)

실행, 디버깅 (F5)

 

2. 오류의 종류

컴파일러 에러 (문법 오류): 코드가 문법적으로 맞지 않아 발생하는 오류

링크 에러: 컴파일은 성공했지만, 필요한 함수나 변수를 찾지 못해 링크 단계에서 발생하는 오류

런타임 에러: 프로그램 실행 중에 발생하는 오류

논리 오류: 코드는 실행되고 종료는 되지만, 의도와 다른 결과를 출력하거나 동작하는 오류

+ Recent posts