본문 바로가기
문제풀이/명품 C++ Programming

[명품 C++ Programming] 4장 실습 문제

by 민됴리 2020. 12. 15.
반응형

2018년에 3월 5일에 발행된

황기태 저자의

명품 C++ Programming 개정판

4장 실습 문제입니다.

 

저작권을 준수하기 위해서

책에 나와있는 문제를 요약해서 적었습니다.

 

궁금한 점은 댓글로 남겨주세요.

 


 

4-1. 코드 빈칸 채우기

	p = &screenColor;
	p->show();
	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();
	}

 

4-2. 정수 배열 동적 할당 및 반환 하기

#include <iostream>
using namespace std;

int main(void) {

	int* arr = new int[5];
	if (!arr)
		return;
	int sum = 0;
	double avg;

	cout << "정수 5개 입력>> ";
	for (int i = 0; i < 5; i++) {
		cin >> arr[i];
	}
	for (int i = 0; i < 5; i++) {
		sum += arr[i];
	}
	avg = (double)sum / 5;
	cout << "평균 " << avg;

	return 0;
}

 

4-3. 입력받은 문자열에 존재하는 'a'의 개수와 'a'의 인덱스 구하기

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

int main(void) {

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

	int count = 0;
	for (int i = 0; i < str.size(); i++) {
		if (str.at(i) == 'a') {
			count++;
		}
	}
	cout << "문자 a는 " << count << "개 있습니다." << endl;

	int index = 0;
	cout << "a의 인덱스: ";
	while ((index = str.find('a', index)) != -1) {
		cout << index << ' ';
		index++;
	}

	return 0;
}

 

4-4. Sample 클래스 완성하기

#include <iostream>
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 big = p[0];
	for (int i = 1; i < size; i++) {
		if (big < p[i])
			big = p[i];
	}
	return big;
}

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

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

 

4-5. 입력받은 영문을 글자 하나만 랜덤하게 수정하여 출력

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

int main(void) {

	srand((unsigned int)time(NULL));

	string str;
	while (true) {
		cout << "아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다.)" << endl;
		cout << ">>";
		getline(cin, str, '\n');
		if (str == "exit") {
			break;
		}
		int n = rand() % str.length();
		char alpha = rand() % 26 + 'a';
		str[n] = alpha;
		cout << str << endl;
	}

	return 0;
}

 

4-6. 입력받은 영문 거꾸로 출력

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

int main(void) {

	string str;
	cout << "아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다.)" << endl;
	while (true) {
		cout << ">>";
		getline(cin, str, '\n');
		if (str == "exit")
			break;
		string reverseStr = str;	//입력받은 문자열의 원본을 훼손하지 않기 위해
		int length = reverseStr.size();
		char temp;
		for (int i = 0; i < length / 2; i++) {
			temp = reverseStr[i];
			reverseStr[i] = reverseStr[length - i - 1];
			reverseStr[length - 1 - i] = temp;
		}
		cout << reverseStr << endl;
	}

	return 0;
}

 

4-7. Circle 클래스 완성하기

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

class Circle {
	int radius;
public:
	void setRadius(int radius) { this->radius = radius; }
	double getArea() { return 3.14 * radius * radius; }
};

int main(void) {

	Circle circleArray[3];

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

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

 

4-8. 7번 문제 변형

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

class Circle {
	int radius;
public:
	void setRadius(int radius) { this->radius = radius; }
	double getArea() { return 3.14 * radius * radius; }
};

int main(void) {

	int num;
	cout << "원의 개수 >> ";
	cin >> num;

	Circle* p = new Circle[num];
	if (!p)
		return 0;

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

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

	delete[] p;

	return 0;
}

 

4-9. 이름과 전화번호를 입력받아 출력하고 검색하는 프로그램

#include <iostream>
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) { this->name = name; this->tel = tel; }
};

int main(void) {

	Person pArray[3];
	string name;
	string tel;

	cout << "이름과 전화 번호를 입력해 주세요" << endl;
	for (int i = 0; i < 3; i++) {
		cout << "사람 " << i + 1 << ">>";
		cin >> name >> tel;
		pArray[i].set(name, tel);
	}

	cout << "모든 사람의 이름은 ";
	for (int i = 0; i < 3; i++) {
		cout << pArray[i].getName() << ' ';
	}
	cout << endl;
	
	cout << "전화번호 검색합니다. 이름을 입력하세요>> ";
	cin >> name;
	int index = -1;
	for (int i = 0; i < 3; i++) {
		if (pArray[i].getName() == name) {
			index = i;
			break;
		}
	}
	if (index == -1) {
		cout << "존재하지 않는 이름입니다." << endl;
	}
	else
		cout << "전화 번호는 " << pArray[index].getTel() << endl;
}

 

4-10. 주어진 코드 완성하기

#include <iostream>
using namespace std;

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

class Family {
	Person* p;
	string familyName;
	int size;
public:
	Family(string familyName, int size) {
		this->familyName = familyName;
		this->size = size;
		p = new Person [size];
	}
	void setName(int num, string name) {
		p[num].setName(name);
	}
	void show() {
		cout << familyName << "가족은 다음과 같이 " << size << "명 입니다." << endl;
		for (int i = 0; i < size; i++) {
			cout << p[i].getName() << '\t';
		}
		cout << endl;
	}
	~Family() {
		delete[]p;
	}
};

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

 

4-11. 커피 자판기 프로그램

#include <iostream>
using namespace std;

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

void Container::fill() {
	size = 10;
}

void Container::consume() {
	size -= 1;
}

int Container::getSize() {
	return size;
}

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

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

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::selectSugarCoffee() {
	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() {
	cout << "***** 커피자판기를 작동합니다. *****" << endl;
	
	int choice;
	while (true) {
		cout << "메뉴를 눌러주세요(1: 에스프레소, 2:아메리카노, 3:설탕커피, 4:잔량보기, 5:채우기)>> ";
		cin >> choice;
		switch (choice) {
		case 1:
			selectEspresso();
			break;
		case 2:
			selectAmericano();
			break;
		case 3:
			selectSugarCoffee();
			break;
		case 4:
			show();
			break;
		case 5:
			fill();
			break;
		}
	}
}

int main(void) {

	CoffeeVendingMachine machine;
	machine.run();
	
	return 0;
}

 

4-12. 주어진 코드 완성하기

#include <iostream>
using namespace std;

class Circle {
	int radius;
	string name;
public:
	void setCircle(string name, int radius);
	double getArea();
	string getName();
};

void Circle::setCircle(string name, int radius) {
	this->name = name;
	this->radius = radius;
}

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

string Circle::getName() {
	return name;
}

class CircleManager {
	Circle* p;
	int size;
public:
	CircleManager(int size);
	~CircleManager();
	void searchByName();
	void searchByArea();
};

CircleManager::CircleManager(int size) {
	this->size = size;
	p = new Circle[size];
	if (!p)
		return;
	string name;
	int radius;
	for (int i = 0; i < size; i++) {
		cout << "원 " << i + 1 << "의 이름과 반지름 >> ";
		cin >> name >> radius;
		p[i].setCircle(name, radius);
	}
}

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

void CircleManager::searchByName() {
	string name;
	cout << "검색하고자 하는 원의 이름 >> ";
	cin >> name;
	for (int i = 0; i < size; i++) {
		if (p[i].getName() == name)
			cout << p[i].getName() << "의 면적은 " << p[i].getArea() << endl;
	}
}

void CircleManager::searchByArea() {
	int area;
	cout << "최소 면적을 정수로 입력하세요 >> ";
	cin >> area;
	cout << area << "보다 큰 원을 검색합니다." << endl;
	for (int i = 0; i < size; i++) {
		if (p[i].getArea() > size) {
			cout << p[i].getName() << "의 면적은 " << p[i].getArea() << ", ";
		}
	}
	cout << endl;
}

int main(void) {

	int size;
	cout << "원의 개수>> ";
	cin >> size;
	CircleManager p(size);
	p.searchByName();
	p.searchByArea();

	return 0;
}

 

4-13. 영문자로 구성된 텍스트가 몇 개의 알파벳을 가지며 각 알파벳의 개수는 몇 개인지 구하기

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

class Histogram {
	string str;
public:
	Histogram(string str);
	void put(string str);
	void putc(char ch);
	void print();
};

Histogram::Histogram(string str) {
	this->str = str;
}

void Histogram::put(string str) {
	this->str += "\n" + str;
}

void Histogram::putc(char ch) {
	this->str += ch;
}

void Histogram::print() {
	int totalAlpha = 0;
	int alphaNum[26] = { 0, };
	cout << str << endl << endl;
	for (int i = 0; i < str.size(); i++) {
		if (isalpha(str[i])) {
			totalAlpha++;
			alphaNum[tolower(str[i]) - 'a'] += 1;
		}
	}
	cout << "총 알파벳 수 " << totalAlpha << endl << endl;

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

int main(void) {

	Histogram elvisHisto("Wise men say, only fools rush in But I can't help, ");
	elvisHisto.put("falling in love with you");
	elvisHisto.putc('-');
	elvisHisto.put("Elvis Presley");
	elvisHisto.print();

	return 0;
}

 

4-14.갬블링 게임

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

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

class GamblingGame {
	Player p[2];
public:
	void run();
	bool turn(string name);
	~GamblingGame();
};

void GamblingGame::run() {
	srand((unsigned)time(NULL));
	cout << "***** 갬블링 게임을 시작합니다. *****" << endl;
	string name;
	cout << "첫번째 선수 이름>>";
	cin >> name;
	p[0].setName(name);
	cout << "두번째 선수 이름>>";
	cin >> name;
	p[1].setName(name);
	cin.ignore();

	int end = 0;
	while (true) {
		for (int i = 0; i < 2; i++) {
			if (turn(p[i].getName())) {
				cout << p[i].getName() << "님 승리!!!" << endl;
				end = 1;
				break;
			}
			else
				cout << "아쉽군요!" << endl;
		}
		if (end == 1)
			break;
	}
}

bool GamblingGame::turn(string name) {
	string enter;
	cout << name << "<Enter>";

	while (true) {
		char ch;
		cin.get(ch);
		if (ch == '\n')
			break;
	}
	
	int random[3] = { 0, };

	for (int i = 0; i < 3; i++) {
		random[i] = rand() % 3;
	}

	cout << "\t" << random[0] << '\t' << random[1] << '\t' << random[2] << '\t';
	if (random[0] == random[1] && random[1] == random[2])
		return true;
	else 
		return false;
}

GamblingGame::~GamblingGame() {
	cout << "게임을 종료합니다." << endl;
}

int main(void) {

	GamblingGame g;
	g.run();

	return 0;
}

 

반응형