C-C++/명품 C++ Programming

[(개정판) 명품 C++ programming] 4장 실습 문제

최옥구 2023. 1. 5. 10:35
반응형

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();
	Color Colors[3];
	p = Colors;

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

	Colors[0].show();
	Colors[1].show();
	Colors[2].show();
}

 


 

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

[결과]

[소스 코드]

#include <iostream>
using namespace std;

int main()
{
	int* p = new int [5];
	int n;
	float sum = 0;
	cout << "정수 5개 입력 >> ";

	for (int i = 0; i < 5; i++)
	{
		cin >> n;
		p[i] = n;
		sum += p[i];
	}
	float regular = sum / 5;

	cout << "평균 " << regular << endl;
	delete p;
}

 


 

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

[결과]

[소스 코드]

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

int main()
{
	cout << "문자열 입력 >> ";
	string inputString;
	getline(cin, inputString);

	int Index = -1;
	int count = 0;
	while (true)
	{
		Index = inputString.find('a', Index + 1);
		if (Index == -1)
			break;
		else
			count++;
	}
	cout << "문자 a는 " << count << "개 있습니다. " << endl;
}

 


 

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

[결과]

[선언부 Sample.h]

#ifndef SAMPLE_H
#define SAMPLE_H

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

#endif

[구현부 Sample.cpp]

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

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 = 0; i < size; i++)
	{
		if (max < p[i])
			max = p[i];
	}
	return max;
}

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

 

[메인 함수]

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

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

 


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

[결과]

[소스 코드]

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

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

		if (str == "exit")
			break;

		int size = str.length();
		int randPos = rand() % (size - 1);
		while (true)
		{
			randPos = rand() % (size - 1);
			if (str[randPos] != ' ')
				break;
		}
		//97~122 영어 소문자 아스키코드
		char randAlpha = (char)(rand() % 26 + 97);
		str[randPos] = randAlpha;

		cout << str << endl;
	}
}

 


 

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

[결과]

[소스 코드]

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

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

		if (str == "exit")
			break;

		for (size; size >= 0; size--)
		{
			cout << str[size];
		}
		cout << endl;
	}
}

 


 

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

[결과]

[선언부 Circle.h]

#ifndef CIRCLE_H
#define CIRCLE_H

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

#endif

[구현부 Circle.cpp]

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

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

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

[메인 함수]

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

int main()
{
	Circle* pArray = new Circle[3];
	int radius;
	cout << "원 1의 반지름 >> ";
	cin >> radius;
	pArray[0].setRadius(radius);

	cout << "원 2의 반지름 >> ";
	cin >> radius;
	pArray[1].setRadius(radius);

	cout << "원 3의 반지름 >> ";
	cin >> radius;
	pArray[2].setRadius(radius);

	int count = 0;
	for (int i = 0; i < 3; i++)
	{
		if (pArray[i].getArea() > 100)
			count++;
	}

	cout << "면적이 100보다 큰 원은 " << count << "개 입니다." << endl;
}

 


 

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

[결과]

[소스 코드]

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

int main()
{
	int num, radius;
	cout << "원의 개수 >> ";
	cin >> num;
	Circle* pArray = new Circle[num];
	for (int i = 0; i < num; i++)
	{
		cout << "원 " << i << "의 반지름 >> ";
		cin >> radius;
		pArray[i].setRadius(radius);
	}

	int count = 0;
	for (int i = 0; i < num; i++)
	{
		if (pArray[i].getArea() > 100)
			count++;
	}

	cout << "면적이 100보다 큰 원은 " << count << "개 입니다." << endl;
}

 


 

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

[결과]

[소스 코드]

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

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

void Person::set(string n, string t)
{
	name = n;
	tel = t;
}

int main()
{
	string name, tel;
	Person* pArray = new Person[3];

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

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

 


 

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

[결과]

[소스 코드]

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

class Family {
    Person* p;
    int size; 
    string name;
public:
    Family(string name, int size);
    void setName(int id, string name) { p[id].setName(name); }
    void show(); 
    ~Family() { delete[] p; }
};

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

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

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;
}

 


11. 다음은 커피자판기로 작동하는 프로그램을 만들기 위해 필요한 두 클래스이다. . . . 다음과 같이 실행되도록 main() 함수와 CoffeeVendingMachine, Container를 완성하라. 만일 커피, 물, 설탕 중 잔량이 하나라도 부족해 커피를 제공할 수 없는 경우 '원료가 부족합니다.'를 출력하라.

[결과]

[소스 코드]

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

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

class CoffeeVendingMachine
{
    Container tong[3]; //tong[0] = 커피, tong[1] = 물, tong[2] = 설탕
    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()
{
    tong[0].consume();
    tong[1].consume();
}

void CoffeeVendingMachine::selectAmericano()
{
    tong[0].consume();
    tong[1].consume();
    tong[1].consume();
}

void CoffeeVendingMachine::selectSugarCoffee()
{
    tong[0].consume();
    tong[1].consume();
    tong[1].consume();
    tong[2].consume();
}

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

void CoffeeVendingMachine::run()
{
    int choice;
    bool machineOn = true;
    cout << "***** 커피 자판기를 작동합니다. *****" << endl;
    while (machineOn)
    {
        cout << "메뉴를 눌러주세요. (1 : 에스프레소, 2 : 아메리카노, 3 : 설탕커피, 4 : 잔량보기, 5 : 채우기, 6 : 장치 종료)" << endl;
        cin >> choice;
        switch (choice)
        {
        case 1:
            selectEspresso();
            cout << "에스프레소 드세요." << endl;
            break;
        case 2:
            selectAmericano();
            cout << "아메리카노 드세요." << endl;
            break;
        case 3:
            selectSugarCoffee();
            cout << "설탕커피 드세요." << endl;
            break;
        case 4:
            show();
            cout << endl;
            break;
        case 5:
            fill();
            show();
            cout << endl;
            break;
        case 6:
            cout << "장치를 종료합니다...";
            machineOn = false;
            break;
        }
    }
}

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

 


12. 다음은 이름과 반지름을 속성으로 가진 Circle 클래스와 이들을 배열로 관리하는 CircleManager 클래스이다. . . . 키보드에서 원의 개수를 입력받고, 그 개수만큼 원의 이름과 반지름을 입력받고, 다음과 같이 실행되도록 main() 함수를 작성하라. Circle, CircleManager 클래스도 작성하라.

[결과]

[소스 코드]

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

class Circle
{
	int radius;
	string name;
public:
	void setCircle(string name, int radius) { this->name = name; this->radius = radius; }
	double getArea() { return radius * radius * 3.14; }
	string getName() { return name; }
};

class CircleManager
{
	int size;
	Circle* p = new Circle[size];
	int radius;
public:
	CircleManager(int size);
	~CircleManager();
	void searchByName();
	void searchByArea();
};

CircleManager::CircleManager(int size)
{
	string name;
	p = new Circle[size];
	this->size = size;
	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 (name == p[i].getName())
		{
			cout << name << "의 면적은 " << p[i].getArea() << endl;
			break;
		}
	}
}

void CircleManager::searchByArea()
{
	int minArea;
	cout << "최소 면적을 정수로 입력하세요. >> ";
	cin >> minArea;
	cout << minArea << "보다 큰 원을 검색합니다. " << endl;

	for (int i = 0; i < size; i++)
	{
		if (p[i].getArea() >= minArea)
		{
			cout << p[i].getName() << "의 면적은 " << p[i].getArea() << ", ";
		}
	}
}

int main() 
{
	int size;
	cout << "원의 개수 >> ";
	cin >> size;
	CircleManager circleManager(size);
	circleManager.searchByName();
	circleManager.searchByArea();
}

 


13. 영문자로 구성된 텍스트에 대해 각 알파벳에 해당하는 문자가 몇 개인지 출력하는 히스토그램 클래스 Histogram을 만들어보자. 대문자는 모두 소문자로 변환하여 처리한다.

[결과]

2장에서 유사한 문제가 나왔었습니다.

[소스 코드]

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

class Histogram
{
	string strTotal;
	char strChar;
	int totalCount = 0;
	int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0, j = 0, k = 0, l = 0, m = 0,
		n = 0, o = 0, p = 0, q = 0, r = 0, s = 0, t = 0, u = 0, v = 0, w = 0, x = 0, y = 0, z = 0;
public:
	Histogram(string str);
	void put(string str);
	void putc(char strChar);
	void print();
};

Histogram::Histogram(string str)
{
	cout << str << endl;
	strTotal += str;
}

void Histogram::put(string str)
{
	cout << str;
	strTotal += str;
}

void Histogram::putc(char strChar)
{
	cout << strChar;
	strTotal += strChar;
}

void Histogram::print()
{
	int alpha[26] = { 0 };
	int num = 0;
	for (int i = 0; i < strTotal.length(); i++)
	{
		if (isalpha(strTotal[i])) 
		{
			char c = tolower(strTotal[i]);
			alpha[c - 'a']++;
			num++;
		}
	}
	cout << endl << endl;
	cout << "총 알파벳 수 " << num;
	cout << endl << endl;
	for (int i = 0; i < 26; ++i)
	{
		char c = 'a' + i;
		cout << c << " (" << alpha[i] << ")\t: ";
		for (int j = 0; j < alpha[i]; ++j) 
		{
			cout << "*";
		}
		cout << endl;
	}
}

int main() 
{
	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();
}

 


14. 겜블링 게임을 만들어보자. 두 사람이 게임을 진행하며, 선수의 이름을 초기에 입력 받는다. 선수가 번갈아 자신의 차례에서 <Enter> 키를 치면 랜덤한 3개의 수가 생성되고, 모두 동일한 수가 나오면 게임에서 이기게 된다. 숫자의 범위가 너무 크면 3개의 수가 일치할 가능성이 낮아 숫자의 범위는 0 ~ 2로 제한한다. 랜덤 정수 생성은 문제 3번의 힌트를 참고하라. 선수는 Player 클래스로 작성하고, 2명의 선수는 배열로 구성하라. 그리고 게임은 GamblingGame 클래스로 작성하라.

[결과]

[소스 코드]

#include<iostream>
#include<string>
#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 = new Player[2];
public:
    GamblingGame();
    void nameSet();
    string ranNum(string n);
    void startGame();
    ~GamblingGame() { delete[] p; }
};

GamblingGame::GamblingGame()
{
    cout << "***** 갬블링 게임을 시작합니다. *****\n";
    srand(time(NULL));
}

void GamblingGame::nameSet() 
{
    string name;
    cout << "첫번째 선수 이름>>";
    cin >> name;
    p[0].setName(name);
    cout << "두번째 선수 이름>>";
    cin >> name;
    p[1].setName(name);
}

string GamblingGame::ranNum(string n)
{
    int r[3];
    cout << "\t\t";
    for (int i = 0; i < 3; i++) 
    {
        r[i] = rand() % 3;
        cout << r[i] << "\t";
    }
    if (r[0] == r[1] && r[0] == r[2])
    {
        n += "님 승리!!";
        return n;
    }
    else
        return "아쉽군요!";
}

void GamblingGame::startGame() 
{
    string n;
    int i = 0;
    while (true) 
    {
        string m;
        cout << p[i % 2].getName() << ":\n";
        getline(cin, n);
        m = p[i % 2].getName();
        n = ranNum(n);
        if (n == "님 승리!!") 
        {
            cout << m + n;
            break;
        }
        else
            cout << n << endl;
        i++;
    }
}

int main()
{
    GamblingGame game;
    game.nameSet();
    game.startGame();
}

 


책에서 나오는 힌트나 조건들의 일부는 저작자 존중을 위해 일부러 작성하지 않았습니다. 

개인 공부용으로 올리는 만큼 풀이에 대한 지적 감사하겠습니다.

반응형