C++ / 복습 (중간)

ChoRong0824·2023년 4월 23일
0

C

목록 보기
15/17
post-thumbnail

중간고사 대비 c++ 실습 & 오픈챌린지 위주 복습



왜 에러가 뜨는 것인지 ? PRIVATE에 넣어서 접근을 못하나?
아닐텐데, 혹시나 몰라서 말고 퍼블릭에 초기화를 해줬는데 ..? 해결되지않는다.
에러는 식별자 에러. 식별자에 대해 다시한번 생각해보고, 코드를 확인했다.
void show(){} 아.. 바보구나, ㅋㅋㅋ
Oval::void show() 를 해줘야한다. 왜냐하면 생성자 함수에 선언을 OVAL.h에 하고, 생성자 구현은 oval.cpp 에 하려고 했는데, 어느 클래스인지 정확하게 앞에 식별자를 안해줘서 생긴 에러이기 때문입니다.

CHAPTER 4 
================9 번 ================================
<<< 메인 클래스 >>>>
#include "Person2.h"

int main() {
	
	cout << "이름과 전화 번호를 입려갷주세요" << endl;
	Person person[3];
	string name, tel;

	for (int i = 0; i < 3; i++){
		cout << "사람 " << i+1 << ">>";
		cin >> name >> tel;
		person[i].set(name, tel);
	}
	cout << "모든 사람의 이름은";
	for (int j = 0; j < 3; j++){
		cout << person[j].getName() << ' ';
	}
	cout << endl;

	cout << "전화번호 검색합니다. 이름을 입력하세요 >>";
	cin >> name;
	int index = -1;
	for (int i = 0; i < 3; i++) {
		if (person[i].getName() == name) {
			index = i;
			break;
		}
	}
	if (index == -1) {
		cout << "존재하지 않는 이름입니다." << endl;
	}
	else
		cout << "전화 번호는 " << person[index].getTel() << endl;
}
<<< 헤더파일 >>>
#ifndef PERSON
#define PERSON

#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);
	~Person();
};
Person::Person(){
}
void Person::set(string name, string tel) {
	this -> name=name;
	this -> tel=tel;
}


Person::~Person()
{
}

#endif // !PERSON

================ 10 번 ================================
<<< 10번 메인 >>>
#include "Family2.h"

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;
}
<<< 10번 펄슨 헤더파일 >>>
#ifndef PERSON
#define PERSON

#include <iostream>
using namespace std;

class Person
{
	string name;
public:
	Person();
	Person(string name) {
		this->name = name;
	}
	string getName() {
		return name;
	}
	// 추가 3.
	void setName(string name) {
		this->name = name;
	}
	~Person();
};

Person::Person() {

}
Person::~Person()
{
}

#endif // !PERSON

<<< 10번 패밀리 헤더파일 >>>
#ifndef FAMILY
#define FAMILY

#include "Person3.h"

class Family
{
	Person* p; // 펄슨 배열 포인터
	int size;
	string familyName; // 추가2, 가족 구성원 이름
public:
	// 추가 4,
	Family(string familyName, int size) {
		this->familyName = familyName;
		this->size = size;
		p= new Person[size]; // 배열 생성
	}
	// 추가 3, 
	void setName(int i, string name) {
		p[i].setName(name);
	}
	void show();
	~Family();

};

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

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


#endif // !FAMILY

================ 12 번 ================================
<<< 12번 코드 1>>>
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

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 3.14 * radius * radius; }
	string getName() { return name; }
};

class CircleManager {
	Circle *p;
	int size;
public:
	CircleManager(int size) { p = new Circle[size]; this->size = size; }
	~CircleManager() { delete [] p; }
	Circle * getCircle() { return p; }
	void searchByName();
	void searchByArea();
};

void CircleManager::searchByName() {
	string find;
	cout << "검색하고자 하는 원의 이름 >> ";
	cin >> find;

	for (int i = 0; i < size; i++) {
		if (find==p[i].getName()) {
		//if (find.compare(p[i].getName()) == 0) {
			cout << p[i].getName() << "의 면적은 " << 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() << ", ";
		}
	}
	cout << endl;
}

int main() {
	int numOfCircles;
	cout << "원의 개수 >> ";
	cin >> numOfCircles;

	CircleManager circles(numOfCircles);

	for (int i = 0; i < numOfCircles; i++) {
		cout << "원 " << i + 1 << "의 이름과 반지름 >> ";
		string name;
		int r;
		cin >> name >> r;
		circles.getCircle()[i].setCircle(name, r);
	}
	circles.searchByName();
	circles.searchByArea();

	return 0;
}
<<< 12번 코드 2>>>
#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;
}
================ 13 번 ================================
<<< 13번 코드 1>>>
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

class Histogram {
	string str;
	int alphabet[26] = { 0 };
public:
	Histogram(string str) { this->str = str; }
	void put(string new_str) { this->str.append(new_str); }
	void putc(char ch) { this->str.append(&ch); }
	void print();
	int getAlphabetSize();
	void countAlphabet();
};

void Histogram::print() {
	cout << str << endl << endl;
	cout << "총 알파벳 수 " << getAlphabetSize() << endl << endl;

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

int Histogram::getAlphabetSize() {
	int cnt = 0;
	for (int i = 0; i < str.length(); i++) {
		if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
			cnt++;
		}
	}
	return cnt;
}


void Histogram::countAlphabet() {
	for (int i = 0; i < str.length(); i++) {
		if (str[i] >= 'A' && str[i] <= 'Z') {
			int ind = str[i] - 'A';
			alphabet[ind]++;
		}
		if (str[i] >= 'a' && str[i] <= 'z'){
			int ind = str[i] - 'a';
			alphabet[ind]++;
		}
	}
}

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();

	return 0;
}
<<< 13번 코드 2>>>
#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;

}




================ 3장  ================================
CHAPTER 3
================9 번 ================================
3-9. Oval 클래스 작성하기

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

Oval::Oval() {
	width = 1;
	height = 1;
}

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

Oval::Oval(int width, int height) {
	this->width = width;
	this->height = height;
}

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

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

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

void Oval::show() {
	cout << "width = " << width << ", height = " << height << endl;
}
 

================ 10 번 _ (1) ================================
(1) 모든 코드를 하나의 cpp 파일에 작성하기
#include <iostream>
using namespace std;

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

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

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

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

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

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

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

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

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

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

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

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

int main(void) {

	Add a;
	Sub s;
	Mul m;
	Div d;
	
	int num1, num2;
	char oper;

	while (true) {
		cout << "두 정수와 연산자를 입력하세요>>";
		cin >> num1 >> num2 >> oper;
		switch (oper) {
		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;
		}
	}

	return 0;
}
 
================ 10 번 _ (2) ================================
(2) 헤더 파일과 cpp 파일로 나누어 작성하기
//Add.h
#ifndef ADD_H
#define ADD_H

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

#endif
//Add.cpp
#include "Add.h"

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

int Add::calculate() {
	return a + b;
}
//Sub.h
#ifndef SUB_H
#define SUB_H

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

#endif
//Sub.cpp
#include "Sub.h"

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

int Sub::calculate() {
	return a - b;
}
//Mul.h
#ifndef MUL_H
#define MUL_H

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

#endif
//Mul.cpp
#include "Mul.h"

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

int Mul::calculate() {
	return a * b;
}
//Div,h
#ifndef DEV_H
#define DEV_H

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

#endif
//Div.cpp
#include "Div.h"

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

int Div::calculate() {
	return a / b;
}
//main.cpp
#include <iostream>
using namespace std;

#include "Add.h"
#include "Sub.h"
#include "Mul.h"
#include "Div.h"

int main(void) {

	Add a;
	Sub s;
	Mul m;
	Div d;

	int num1, num2;
	char oper;

	while (true) {
		cout << "두 정수와 연산자를 입력하세요>>";
		cin >> num1 >> num2 >> oper;
		switch (oper) {
		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;
		}
	}

	return 0;
}
================ 2장 ==================================
16번
================ 16 번 ===============================
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

int main() {
	char str[10000];
	int alphabet[26] = { 0 }, ind;

	cout << "영문 텍스트를 입력하세요. 히스토그램을 그립니다. 텍스트의 끝은 ;입니다. 10000개까지 가능합니다.\n";
	cin.getline(str, 10000, ';');
	cout << "총 알파벳 수 " << strlen(str) << '\n';

	for (int i = 0; i < strlen(str); i++)
	{
		if (str[i] >= 'A' && str[i] <= 'Z')
		{
			ind = (int)(str[i] - 'A');
			alphabet[ind]++;
		}
		else if (str[i] >= 'a' && str[i] <= 'z')
		{
			ind = (int)(str[i] - 'a');
			alphabet[ind]++;
		}
		else { }
	}

	for (int i = 0; i < 26; i++)
	{
		cout << (char)('a' + i) << " ("<<alphabet[i]<<")\t : ";
		for (int j = 0; j < alphabet[i]; j++)
		{
			cout << "*";
		}
		cout<<"\n";
	}
	return 0;
}
Chapter 3. 클래스와 객체
1번
main()의 실행 결과가 다음과 같도록 Tower 클래스를 작성하라.

소스 코드

#include <iostream>

using namespace std;

class Tower {
public:
	int height;
	Tower();
	Tower(int height);
	int getHeight();
};

Tower::Tower()
{
	height = 1;
}

Tower::Tower(int height)
{
	this->height = height;
}

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

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


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

소스 코드

#include <iostream>
#include <string>

using namespace std;

class Date {
public:
	int year;
	int month;
	int day;
	Date(int year, int month, int day);
	Date(string date);
	void show();
	int getYear();
	int getMonth();
	int getDay();
};

Date::Date(int year, int month, int day)
{
	this->year = year;
	this->month = month;
	this->day = day;
}
Date::Date(string date)
{
	int ind;

	this->year = stoi(date);

	ind = date.find('/');
	this->month = stoi(date.substr(ind + 1));

	ind = date.find('/', ind + 1);
	this->day = stoi(date.substr(ind + 1));
}
void Date::show()
{
	cout << year << "년" << month << "월" << day << "일" << endl;
}
int Date::getYear()
{
	return year;
}
int Date::getMonth()
{
	return month;
}
int Date::getDay()
{
	return day;
}

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

	return 0;
}


3번
은행에서 사용하는 프로그램을 작성하기 위해, 은행 계좌 하나를 표현하는 클래스 Account가 필요하다. 계좌 정보는 계좌의 주인, 계좌 번호, 잔액을 나타내는 3 멤버 변수로 이루어진다. main() 함수의 실행 결과가 다음과 같도록 Account 클래스를 작성하라.

소스 코드

#include <iostream>
#include <string>

using namespace std;

class Account {
public:
	string name;
	int id;
	int balance;
	Account(string name, int id, int balance);
	void deposit(int money);
	int withdraw(int money);
	int inquiry();
	string getOwner();
};

Account::Account(string name, int id, int balance)
{
	this->name = name;
	this->id = id;
	this->balance = balance;
}
void Account::deposit(int money)
{
	balance += money;
}
int Account::withdraw(int money)
{
	balance -= money;
	return balance;
}
int Account::inquiry()
{
	return balance;
}
string Account::getOwner()
{
	return name;
}

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


4번
CoffeeMachine 클래스를 만들어보자. main() 함수와 실행 결과가 다음과 같도록 CoffeMachine 클래스를 작성하라. 에스프레소 한 잔에는 커피와 물이 각각 1씩 소비되고, 아메리카노의 경우 커피는 1, 물은 2가 소비되고, 설탕 커피는 커피 1, 물 2, 설탕 1이 소비된다. CoffeeMachine 클래스에는 어떤 멤버 변수와 어떤 멤버 함수가 필요한지 잘 판단하여 작성하라.

소스 코드

#include <iostream>
#include <string>

using namespace std;

class CoffeeMachine {
private:
	int coffee;
	int water;
	int sugar;
public:
	CoffeeMachine(int coffee, int water, int sugar);
	void drinkEspresso();
	void drinkAmericano();
	void drinkSugerCoffee();
	void show();
	void fill();
};

CoffeeMachine::CoffeeMachine(int coffee, int water, int sugar)
{
	this->coffee = coffee;
	this->water = water;
	this->sugar = sugar;
}
void CoffeeMachine::drinkEspresso()
{
	coffee = coffee - 1;
	water = water - 1;
}
void CoffeeMachine::drinkAmericano()
{
	coffee = coffee - 1;
	water = water - 2;
}
void CoffeeMachine::drinkSugerCoffee()
{
	coffee = coffee - 1;
	water = water - 2;
	sugar = sugar - 1;
}
void CoffeeMachine::show()
{
	cout << "커피 머신 상태, 커피:" << coffee << "\t물:" << water << "\t설탕:" << sugar << endl;
}
void CoffeeMachine::fill()
{
	coffee = 10;
	water = 10;
	sugar = 10;
}

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


5번
랜덤 수를 발생시키는 Random 클래스를 만들자. Random 클래스를 이용하여 랜덤한 정수를 10개 출력하는 사례는 다음과 같다. Random 클래스가 생성자, next(), nextInRange()의 3개의 멤버 함수를 가지도록 작성하고 main() 함수와 합쳐 하나의 cpp 파일에 구현하라.

소스 코드

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

class Random {
	int seed = 0;
public:
	int next();
	int nextInRange(int start, int end);
};

int Random::next() {
	//srand((unsigned int)time(0));
	int n = rand();
	return n;
}
int Random::nextInRange(int start, int end) {
	//srand((unsigned int)time(0));
	int n = rand() % (end - start + 1) + start;
	return n;
}

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


6번
문제 5번을 참고하여 짝수 정수만 랜덤하게 발생시키는 EvenRandom 클래스를 작성하고 EvenRandom 클래스를 이용하여 10개의 짝수를 랜덤하게 출력하는 프로그램을 완성하라. 0도 짝수로 처리한다.

소스 코드

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

class Random {
	int seed = 0;
public:
	int next();
	int nextInRange(int start, int end);
};

int Random::next() {
	//srand((unsigned int)time(0));
	int n;
	do {
		n = rand();
	} while (n % 2 == 1);
	return n;
}
int Random::nextInRange(int start, int end) {
	//srand((unsigned int)time(0));
	int n;
	do {
		n = rand() % (end - start + 1) + start;
	} while (n % 2 == 1);
	return n;
}

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에서 10까지의 랜덤 정수 10개 --" << endl;
	for (int i = 0; i < 10; i++) {
		int n = r.nextInRange(2, 10);
		cout << n << ' ';
	}
	cout << endl;
	return 0;
}


7번
문제 5번을 참고하여 생성자를 이용하여 짝수 홀수를 선택할 수 있도록 SelectableRandom 클래스를 작성하고 짝수 10개, 홀수 10개를 랜덤하게 발생시키는 프로그램을 작성하라.

소스 코드

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

class SelectableRandom {
	int seed = 0;
public:
	int nextEven();
	int nextOdd();
	int nextEvenInRange(int start, int end);
	int nextOddInRange(int start, int end);
};

int SelectableRandom::nextEven() {
	//srand((unsigned int)time(0));
	int n;
	do {
		n = rand();
	} while (n % 2 != 0);
	return n;
}
int SelectableRandom::nextOdd() {
	//srand((unsigned int)time(0));
	int n;
	do {
		n = rand();
	} while (n % 2 != 1);
	return n;
}
int SelectableRandom::nextEvenInRange(int start, int end) {
	//srand((unsigned int)time(0));
	int n;
	do {
		n = rand() % (end - start + 1) + start;
	} while (n % 2 != 0);
	return n;
}
int SelectableRandom::nextOddInRange(int start, int end) {
	//srand((unsigned int)time(0));
	int n;
	do {
		n = rand() % (end - start + 1) + start;
	} while (n % 2 != 1);
	return n;
}

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


8번
int 타입의 정수를 객체화한 Integer 클래스를 작성하라. Integer의 모든 멤버 함수를 자동 인라인으로 작성하라. Integer 클래스를 활용하는 코드는 다음과 같다.

소스 코드

#include <iostream>
#include <string>

using namespace std;

class Integer {
public:
	int n;
	Integer(int n) {
		this->n = n;
	}
	Integer(string str) {
		this->n = stoi(str);
	}
	void set(int n) {
		this->n = n;
	}
	int get(){
		return n;
	}
	bool isEven() {
		if (n % 2 == 0) return true;
		else return false;
	}
};

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

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

	return 0;
}


9번
Oval 클래스는 주어진 사각형에 내접하는 타원을 추상화한 클래스이다. Oval 클래스의 멤버는 모두 다음과 같다. Oval 클래스를 선언부와 구현부로 나누어 작성하라.

소스 코드

#include <iostream>
#include <string>

using namespace std;

class Oval {
private:
	int width;
	int height;
public:
	Oval() {
		width = height = 1;
	}
	Oval(int width, int height) {
		this->width = width;
		this->height = height;
	}
	~Oval() {
		cout << "Oval 소멸 : width = " << width << ", height = " << height << endl;
	}
	void show() {
		cout << "width = " << width << ", height = " << height << endl;
	}
	void set(int width, int height) {
		this->width = width;
		this->height = height;
	}
	int getWidth() {
		return width;
	}
	int getHeight() {
		return height;
	}
};

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

	return 0;
}


10-1번
클래스의 선언부와 구현부를 분리하고, 모든 코드를 Calculator.cpp 파일에 작성하라.

소스 코드

#include <iostream>
#include <string>

using namespace std;

class Add {
	int a, b;
public:
	void setValue(int x,int y){
		a = x; b = y;
	}
	int calculate() {
		return a + b;
	}
};

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

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

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

int main() {
	Add a;
	Sub s;
	Mul m;
	Div d;
	while (true) {
		cout << "두 정수와 연산자를 입력하세요>>";
		int x, y;
		char op;
		cin >> x >> y >> op;

		switch (op) {
		case '+':
			a.setValue(x, y);
			cout << a.calculate() << endl;
			break;
		case '-':
			s.setValue(x, y);
			cout << s.calculate() << endl;
			break;
		case '*':
			m.setValue(x, y);
			cout << m.calculate() << endl;
			break;
		case '/':
			d.setValue(x, y);
			cout << d.calculate() << endl;
			break;
		default:
			break;
		}
	}

	return 0;
}
10-2번
클래스의 선언부와 구현부를 헤더 파일과 cpp 파일로 나누어 프로그램을 작성하라.

소스 코드

calculator.h
#ifndef CALCULATOR_H
#define CALCULATOR_H

class Add {
	int x, y;
public:
	void setValue(int x, int y);
	int calculate();
};

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

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

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

#endif
calculator.cpp
#include <iostream>
#include <string>
#include "calculator.h"

using namespace std;

void Add::setValue(int x, int y) {
	this->x = x;
	this->y = y;
}

int Add::calculate() {
	return x + y;
}

void Sub::setValue(int x, int y) {
	this->x = x;
	this->y = y;
}

int Sub::calculate() {
	return x - y;
}

void Mul::setValue(int x, int y) {
	this->x = x;
	this->y = y;
}

int Mul::calculate() {
	return x * y;
}

void Div::setValue(int x, int y) {
	this->x = x;
	this->y = y;
}

int Div::calculate() {
	return x / y;
}

int main() {
	Add a;
	Sub s;
	Mul m;
	Div d;
	while (true) {
		cout << "두 정수와 연산자를 입력하세요>>";
		int x, y;
		char op;
		cin >> x >> y >> op;

		switch (op) {
		case '+':
			a.setValue(x, y);
			cout << a.calculate() << endl;
			break;
		case '-':
			s.setValue(x, y);
			cout << s.calculate() << endl;
			break;
		case '*':
			m.setValue(x, y);
			cout << m.calculate() << endl;
			break;
		case '/':
			d.setValue(x, y);
			cout << d.calculate() << endl;
			break;
		default:
			break;
		}
	}

	return 0;
}


11번
다음 코드에서 Box 클래스의 선언부와 구현부를 Box.h, Box.cpp 파일로 분리하고 main() 함수 부분을 main.cpp로 분리하여 전체 프로그램을 완성하라.

소스 코드

Box.h
#ifndef BOX_H
#define BOX_H
class Box {
	int width, height;
	char fill;
public:
	Box(int w, 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 i = 0; i < height; i++) {
		for (int j = 0; j < width; j++) {
			cout << fill;
		}
		cout << endl;
	}
}
main.cpp
#include "Box.h"

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

	return 0;
}


12번
컴퓨터의 주기억장치를 모델링하는 클래스 Ram을 구현하려고 한다. Ram 클래스는 데이터가 기록될 메모리 공간과 크기 정보를 가지고, 주어진 주소에 데이터를 기록하고(write), 주어진 주소로부터 데이터를 읽어온다(read). Ram 클래스는 다음과 같이 선언된다. 실행결과를 참고하여 Ram.h, Ram.cpp, main.cpp로 헤더 파일과 cpp 파일을 분리하여 프로그램을 완성하라.

소스 코드

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 <string>
#include "Ram.h"

using namespace std;

Ram::Ram() {
	for (int i = 0; i < 100 * 1024; i++) {
		mem[i] = 0;
	}
	size = 100 * 1024;
}
Ram::~Ram() {
	cout << "메모리 제거됨" << endl;
}
char Ram::read(int address) {
	return mem[address];
}
void Ram::write(int address, char value) {
	mem[address] = value;
}

main.cpp
#include "Ram.h"

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;

	return 0;
}

==========================================================
==========================================================

[2장 연습문제]

1. c++ 응용프로그램이 실행을 시작하는 함수의 원형은 무엇인가?

A. int main()

 

2. C++에서 main() 함수에 대한 설명 중 틀린 것은?

A. 3번 “main() 함수는 반드시 return문을 가지고 있어야 한다.”

C++에서는 main() 함수 끝에 return 0;을 생략할 경우 자동으로 작성됩니다.

 

3. 다음 소스에서 생략해도 되는 라인은 어디인가?

#include <iostream>

int main() {

std::cout << “I love C++\n”;

std::cout << “I love programming”;

return 0;

}

A. C++에서 return 0;을 생략해도 자동으로 작성되기 때문에 retrun 0; 부분은 생략해도 무방합니다.

 

4. 다음 코드는 c컴파일러로 컴파일하면 컴파일 오류가 발생하지만 c++컴파일러로 컴파일하면 정상적으로 컴파일된다.

int a;

a = 4;

int square = a * a;
(1) c 컴파일러로 컴파일할 때 어떤 컴파일 오류가 발생하는가?

A. [형식 오류]. 형식 오류 c언어에서는 모든 변수가 실행문 전에 선언되어야 하므로 컴파일 오류가 발생

(2) c++ 컴파일러로 컴파일할 때 정상적으로 컴파일되는 것은 c++언어의 어떤 특성 때문인가?

A. 프로그램 어디서나 변수 선언이 가능한 성질

(3) 이 특징이 가진 장단점은 무엇인가?

A. 장점은 스크롤을 올렸다 내렸다 해야 하는 번거로움 줄일 수 있고, 변수가 필요할 때 바로 선언할 수 있어서 편하다. 단점은 선언된 변수들이 코드 사이에 흩어져 있으므로 선언된 모든 변수 한눈에 보기 힘들고 찾기도 어렵다.

 

5. 다음 프로그램의 실행 결과는 무엇인가?

#include<iostream>

int main()

{

std::cout << "I love C++\n" << "I love programing";

}
A.

I love C++

I love programing

 

6. 다음 프로그램에 컴파일 오류가 발생하지 않도록 빈칸을 채워라.

(1)

#include<iostream>

_________________________

int main()

{

int count = 0;

std::cin >> count;

cout << count + 1;

return 0;

}
(2)

#include<iostream>

__________________________

int main()

{

cout << "I love C++" << endl;

cout << "I love programming";

}
(1) using namespace std;

(2) using namespace std;

 

7. 다음 C++ 프로그램 코드에서 틀린 부분을 수정하라.

(1) #include <iostream>;

A. ; 지우기

(2) using namespace std

A. ; 추가

(3) std::cin << name;

A. std::cin >> name;

(4) std:cout<<1<<2<<'a'<<"hello"<<'/n';

A. std::cout << 1 << 2 << 'a' << "hello\n";

 

8. 다음 C++ 프로그램 코드에서 틀린 부분이 있으면 수정하라.

(1) using std::cin;

A. 틀린 부분 없음

(2) int year = 1; //year은 연도를 나타낸다.

A. 틀린 부분 없음

(3) int n=1; cout>>n+200;

A. cout은 << 연산자와 사용해야 한다 =>> int n=1; cout<<n+200;

(4) int year = 2004; cout<<2014+“년”;

A.  포인터를 더할  없기 때문에 <<연산자로 이어주어야 한다

int year = 2004; cout<<year<<“년”;

 

9. 다음은 개발자가 작성한 myheader.h 파일의 소스이다.

#define MAX 100

#define MIN 0
다음 myprog.cpp 프로그램에서 빈칸에 적절한 라인을 삽입하라.

#include <iostream>

using namespace std;

_____________________ //이 곳에 myheader.h를 include하는 문을 작성하라.

int main() {

cout << MAX << MIN;

return 0;

}

A. #inlcude "myheader.h"

 

10. C++ 문자열에 대한 다음 질문에 O, X로 답하라.

C-스트링이란 C언어에서 문자열을 다루는 방식이다.( O )
C++에서 C-스트링 방식의 문자열이 사용된다. ( O )
C++에서는 문자열을 다루기 위해 string클래스가 이용된다.( O , cin.getline()도 이용됨 )
char name[]="C++";이 컴파일되면 name[] 배열의 크기가 3이 된다.( X, 배열의 크기는 4가 된다. )
char name[10]; cin >> name;를 실행하면 공백 문자를 포함하여 키보드로부터 최대 9개의 문자를 읽을 수 있다.(O)
 

11. C-스트링을 다루기 위해, strcmp(), strlen() 등의 함수를 사용하고자 할 때 include 해야 하는 표준 헤더 파일은 무엇인가?

A. #include <cstring>

 

12. 다음 프로그램이 있다.

#include <iostream>

int main() {

char name[20];

std::cout << “이름을 입력하세요?”;

std::cin >> name;

std::cout << name << “님 환영합니다”;

return 0;

}
(1) 프로그램을 실행하고 다음과 같이 키보드로 kitae를 입력한 결과는 무엇인가?

A. kitae님 환영합니다 라고 출력된다.

(2) 프로그램을 실행하고 다음과 같이 키보드로 kitae Hwang을 입력한 결과는 무엇인가?

A. cin의 경우 공백을 구분자로 하기 때문에 Kitae님 환영합니다 라고 출력된다.

 

13. cin.getline(buf, 100. ';')에 대한 설명으로 틀린 것은?

A. 4번 cin.getline(buf,100);로 써도 무관하다.

왜냐하면 cin.getline() 함수의 경우 구분자의 디폴트 값이 ‘\n’ 이므로 ‘;’를 생략하면 안 된다.

 

14. char buf[100];가 선언되어 있다고 가정하고, 다음과 같이 <Enter> 키가 입력될 때까지 문자열을 읽는 코드로 잘못된 것은 무엇인가?

I love C++<Enter>
A. 4번 cin.getline(buf,11,'.');

1,2,3번은 문자열을 입력받고 엔터키를 받으면 getline() 함수가 종료된다.

그러나 4번은 '.'을 받아야만 getline() 함수가 종료된다.

 

15. C++에서 여러 사람들이 나누어 프로그램을 개발할 때 동일한 이름의 변수나 클래스. 함수 등이 충돌하는 것을 막기 위해. 개발자가 자신만의 이름 공간을 생성할 수 있도록 새로 도입한 키워드(혹은 개념)는 무엇인가?

namespace

 

16. C++ 표준 라이브러리가 모두 선언된 이름 공간은 무엇인가?

std

 

17. C++ 표준에서 입출력을 위한 클래스. 함수, 객체들이 포함된 이름 공간은 무엇인가?

std

 

 

18. C++ 표준에서 cin, cout 객체는 어떤 헤더 파일에 선언되어 있는가?

iostream

 

 

19. 다음은 화면에 나이와 학과를 출력하는 main.cpp 프로그램을 작성한 사례이다. 빈칸에 적절한 코드를 삽입하라.

#include <iostream>

using namespace std;

int main() {

int age = 20;

char* pDept = “컴퓨터 공학과”;

_______________________________

}



출력결과 :20 컴퓨터 공학과

A. cout << age << " " << pDept;

 

20. 다음 출력 결과와 같은 코드를 작성하고자 한다. 다음 C++ 프로그램을 완성하라.

#include <iostream>

using namespace std;

int main() {

for(int n=0; n<4; n++) {

_______________________________

_______________________________

_______________________________

}

}



출력 결과:

*

**

***

****
A.

for (int m =0; m <= n; m++) {

cout << "*";

} cout << endl;

 

[2장 실습 문제]
 

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

[코드]

#include <iostream>
using namespace std;

int main()
{
	int n = 1;
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			cout << n << '\t';
			n++;
		}
		cout << endl;
	}
}
[실행결과]


 

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

[코드]

#include <iostream>
using namespace std;

int main()
{
	for (int i = 1; i < 10; i++)
	{
		for (int j = 1; j < 10; j++) cout << j << "x" << i << "=" << i * j << '\t';
		cout << endl;
	}
}
[실행결과]


 

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

[코드]

#include <iostream>
using namespace std;
int main() 
{
	int n,m;

	cout << "두 수를 입력하라>>";
	cin >> n >> m;

	if (n > m) cout << "큰 수 = " << n << endl;
	else if (n < m) cout << "큰 수 = " << m << endl;
	else cout << "두 수는 같습니다." << endl;
	
}
[실행결과]


 

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

[코드]

#include <iostream>
using namespace std;

int main()
{
	double arr[5];
	double max = 0;
	cout << "다섯개의 실수를 입력하라>>";
	
	for (int i = 0; i < 5; i++)
	{
		cin >> arr[i];
		if (i == 0) max = arr[0];
		if (max < arr[i]) max = arr[i];
	}
		
	cout << "제일 큰 수 = " << max << endl;
	
}
[실행결과]


 

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

[코드]

#include<iostream>
using namespace std;

int main()
{
	char c[100];
	int cnt = 0;
	cout << "문자들을 입력하라(100개 미만).\n";
	cin.getline(c, 100, '\n');

	for (int i = 0; i < 100; i++)
	{
		if (c[i] == 'x') cnt++;
	}

	cout << "x의 개수는 " << cnt << endl;

}
[실행결과]


 

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

[코드]

#include<iostream>
using namespace std;

int main()
{
	string a, b;
	cout << "새 암호를 입력하세요>>";
	cin >> a;
	cout << "새 암호를 다시 한 번 입력하세요>>";
	cin >> b;

	if (a == b) cout << "같습니다." << endl;
}
[실행결과]


 

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

[코드]

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

int main()
{
	char c[100];
	
	while (true)
	{
		cout << "종료하고싶으면 yes를 입력하세요>>";
		cin.getline(c, 100, '\n');

		if (strcmp(c,"yes") == 0) break;
	}
	cout << "종료합니다..." << endl;
}
[실행결과]


 

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

[코드]

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

int main()
{
	string ans;
	char name[100];
	int max = 0;
	int n = 0;
	cout << "5 명의 이름을 ';'으로 구분하여 입력하세요\n" << ">>";
	
	for (int i = 1; i <= 5; i++)
	{
		cin.getline(name, 100, ';');
		cout << i << " : " << name;
		cout << endl;

		if (max < strlen(name))
		{
			max = strlen(name);
			n = i;
			ans = name;
		}
			
	}

	cout << "가장 긴 이름은 " << ans << endl;
	
}
[실행결과]


 

9. 이름, 주소, 나이를 입력받아 다시 출력하는 프로그램을 작성하라.

[코드]

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

int main()
{
	string name, address, age;
	cout << "이름은?";
	getline(cin,name);
	cout << "주소는?";
	getline(cin, address);
	cout << "나이는?";
	getline(cin, age);
	
	cout << name << ", " << address << ", " << age << endl;
}
[실행결과]


 

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

[코드]

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

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

	for (int i = 0; i < s.length(); i++)
	{
		for (int j = 0; j <= i; j++)
		{
			cout << s[j];
		}
		cout << '\n';
	}

}
[실행결과]


 

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

#include<stdio.h>

int main()
{
	int k, n = 0;
	int sum = 0;
	printf("끝수를 입력하세요>>");
	scanf("%d", &n);
	for (k = 0; 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 = 0; k <= n; k++)
	{
		sum += k;
	}

	cout << "1에서 " << n << "까지의 합은 " << sum << " 입니다.\n";
}
[실행결과]


 

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

#include<stdio.h>
int sum(); // 함수 원형 선언

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

	return res;
}

int main()
{
	int n = 0;
	printf("끝수를 입력하세요>>");
	scanf("%d", &n);
	printf("1에서 %d까지의 합은 %d 입니다.\n", n, sum(1,n));
	return 0;
}
[코드]

#include<iostream>
using namespace std;

int sum(); // 함수 원형 선언

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

	return res;
}

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


 

13. 덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/), 나머지(%)의 정수 5칙 연산을 할 수 있는 프로그램을 작성하라. 식은 다음과 같은 형식으로 입력된다, 정수와 연산자는 하나의 빈칸으로 분리된다.

[직관적 코드]

#include <iostream>
using namespace std;

int main() 
{
	int a, c;
	char b;
	while (true) 
	{
		cout << "? ";
		cin >> a >> b >> c;
		switch (b) {
		case '+':cout << a << " " << b << " " << c << " = " << a + c << endl; break;
		case '-':cout << a << " " << b << " " << c << " = " << a - c << endl; break;
		case '*':cout << a << " " << b << " " << c << " = " << a * c << endl; break;
		case '/':cout << a << " " << b << " " << c << " = " << a / c << endl; break;
		case '%':cout << a << " " << b << " " << c << " = " << a % c << endl; break;
		default: cout << "잘못된 연산자 입니다." << endl;
		}
	}
}

[문제의 힌트를 활용한 코드]

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

int main() 
{
	int a, c;
	char *b;

	while (true)
	{
		cout << "? ";
		char s[100];
		cin.getline(s, 100, '\n');
		a = atoi(strtok(s, " "));
		b = strtok(NULL, " ");
		c = atoi(strtok(NULL, " "));

		switch (*b)
		{
		case '+':
			cout << a << " + " << c << " = " << a + c << endl; break;
		case '-':
			cout << a << " - " << c << " = " << a - c << endl; break;
		case '*':
			cout << a << " * " << c << " = " << a * c << endl; break;
		case '/':
			cout << a << " / " << c << " = " << a / c << endl; break; 
		case '%':
			cout << a << " % " << c << " = " << a % c << endl; break;
		}

		
	}


}


 

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

[코드]

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

int main() 
{
	char c[10001];
	int cnt[26] = { 0, };
	cin.getline(c, 10000, ';');
	
	for (int i = 0; i < strlen(c); i++)
	{
		cnt[int(c[i])-97]++;
	}

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


}

==========================================================
==========================================================

Chapter 4. 객체 포인터와 객체 배열, 객체의 동적 생성
1번
소스 코드

#include <iostream>
#include <string>

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;
	p->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();
	}
	return 0;
}


2번
소스 코드

#include <iostream>
#include <string>

using namespace std;

int main() {
	int* arr = new int[5];
	float average = 0.0f;

	cout << "정수 5개 입력>>";
	for (int i = 0; i < 5; i++) {
		cin >> arr[i];
		average += arr[i];
	}

	average /= 5;
	cout << "평균 " << average << endl;

	return 0;
}


3-1번
소스 코드

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str;
	int cnt = 0;

	cout << "문자열 입력>>";
	getline(cin, str);
	for (int i = 0; i < str.length(); i++) {
		if (str[i] == 'a') cnt++;
	}

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

	return 0;
}


3-2번
소스 코드

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str;
	int cnt = 0, ind = 0;

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

	while (true) {
		ind = str.find('a', ind+1);
		if (ind == -1) break;
		else cnt++;
	}
	cout << "문자 a는 " << cnt << "개 있습니다." << endl;

	return 0;
}


4번
소스 코드

#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 = 0;
	for (int i = 0; i < size; i++) {
		if (p[i] > max)
			max = p[i];
	}
	return max;
}
Sample::~Sample() {
	delete [] p;
}

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

	return 0;
}


5번
소스 코드

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

int main() {
	string str;

	while (true) {
		getline(cin, str);
		if (str.compare("exit") == 0) break;

		srand((unsigned)time(0));
		int n = rand() % (str.length());

		srand((unsigned)time(0));
		char ch = 'a' + rand() % 26;

		str[n] = ch;

		cout << ">>" << str << endl;
	}

	return 0;
}


6번
소스 코드

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

int main() {
	string str;

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

		for (int i = str.length() - 1; i >= 0; i--) {
			cout << str[i];
		}
		cout << endl;
	}

	return 0;
}


7번
소스 코드

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

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 circles[3];
	int cnt = 0;

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

		if (circles[i].getArea() > 100) {
			cnt++;
		}
	}
	cout << "면적이 100보다 큰 원은 " << cnt << "개 입니다." << endl;

	return 0;
}


8번
소스 코드

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

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() {
	int cnt = 0, numOfCircles;

	cout << "원의 개수>>";
	cin >> numOfCircles;
	Circle *circles = new Circle[numOfCircles];

	for (int i = 0; i < numOfCircles; i++) {
		int r;
		cout << "원 " << i + 1 << "의 반지름 >> ";
		cin >> r;
		circles[i].setRadius(r);

		if (circles[i].getArea() > 100) {
			cnt++;
		}
	}
	cout << "면적이 100보다 큰 원은 " << cnt << "개 입니다." << endl;

	return 0;
}


9번
소스 코드

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

class Person {
	string name;
	string tel;
public:
	Person();
	string getName() { return name; }
	string getTal() { 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 person[3];
	cout << "이름과 전화번호를 입력해 주세요" << endl;

	for (int i = 0; i < 3; i++) {
		cout << "사람 " << i+1 << ">> ";
		string name, tel;
		cin >> name >> tel;
		person[i].set(name, tel);
	}

	cout << "모든 사람의 이름은 ";
	for (int i = 0; i < 3; i++) {
		cout << person[i].getName() << ' ';
	}
	cout << endl;

	cout << "전화번호 검색합니다. 이름을 입력하세요>>";
	string find;
	cin >> find;
	for (int i = 0; i < 3; i++) {
		if (find.compare(person[i].getName()) == 0) {
			cout << "전화 번호는 " << person[i].getTal() << endl;
			break;
		}
	}
	return 0;
}


10번
소스 코드

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

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;
	string familyName;
	int size;
public:
	Family(string name, int size);
	void show();
	void setName(int index, string name) { p[index].setName(name); }
	~Family();
};

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


11번
소스 코드

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

class Container {
	int size;
public:
	Container() { size = 10; }
	void fill() { size = 10; }
	void consume() { size = size - 1; }
	int 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();
	show();
}
void CoffeeVendingMachine::selectEspresso() {
	if (tong[0].getSize() >= 1 && tong[1].getSize() >= 1) {
		tong[0].consume();
		tong[1].consume();
		cout << "에스프레소 드세요" << endl;
	}
	else {
		cout << "원료가 부족합니다" << endl;
	}
}
void CoffeeVendingMachine::selectAmericano() {
	if (tong[0].getSize() >= 1 && tong[1].getSize() >= 2) {
		tong[0].consume();
		tong[1].consume();
		tong[1].consume();
		cout << "아메리카노 드세요" << endl;
	}
	else {
		cout << "원료가 부족합니다" << endl;
	}
}
void CoffeeVendingMachine::selectSugarCoffee() {
	if (tong[0].getSize() >= 1 && tong[1].getSize() >= 2 && tong[2].getSize() >= 1) {
		tong[0].consume();
		tong[1].consume();
		tong[1].consume();
		tong[2].consume();
		cout << "설탕커피 드세요" << endl;
	}
	else {
		cout << "원료가 부족합니다" << endl;
	}
}
void CoffeeVendingMachine::show() {
	cout << "커피 " << tong[0].getSize() << ", 물 " << tong[1].getSize() << ", 설탕 " << tong[2].getSize() << endl;
}
void CoffeeVendingMachine::run() {
	cout << "***** 커피자판기를 작동합니다. *****" << endl;

	while (true) {
		int num;
		cout << "메뉴를 눌러주세요(1:에스프레소, 2:아메리카노, 3:설탕커피, 4:잔량보기, 5:채우기)>>)";
		cin >> num;
		switch (num) {
		case 1:
			selectEspresso();
			break;
		case 2:
			selectAmericano();
			break;
		case 3:
			selectSugarCoffee();
			break;
		case 4:
			show();
			break;
		case 5:
			fill();
			break;
		default:
			break;
		}
	}
}

int main() {
	CoffeeVendingMachine coffeeVendingMachine;
	coffeeVendingMachine.run();
	return 0;
}


12번
소스 코드

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

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 3.14 * radius * radius; }
	string getName() { return name; }
};

class CircleManager {
	Circle *p;
	int size;
public:
	CircleManager(int size) { p = new Circle[size]; this->size = size; }
	~CircleManager() { delete [] p; }
	Circle * getCircle() { return p; }
	void searchByName();
	void searchByArea();
};

void CircleManager::searchByName() {
	string find;
	cout << "검색하고자 하는 원의 이름 >> ";
	cin >> find;

	for (int i = 0; i < size; i++) {
		if (find==p[i].getName()) {
		//if (find.compare(p[i].getName()) == 0) {
			cout << p[i].getName() << "의 면적은 " << 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() << ", ";
		}
	}
	cout << endl;
}

int main() {
	int numOfCircles;
	cout << "원의 개수 >> ";
	cin >> numOfCircles;

	CircleManager circles(numOfCircles);

	for (int i = 0; i < numOfCircles; i++) {
		cout << "원 " << i + 1 << "의 이름과 반지름 >> ";
		string name;
		int r;
		cin >> name >> r;
		circles.getCircle()[i].setCircle(name, r);
	}
	circles.searchByName();
	circles.searchByArea();

	return 0;
}


13번
소스 코드

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

class Histogram {
	string str;
	int alphabet[26] = { 0 };
public:
	Histogram(string str) { this->str = str; }
	void put(string new_str) { this->str.append(new_str); }
	void putc(char ch) { this->str.append(&ch); }
	void print();
	int getAlphabetSize();
	void countAlphabet();
};

void Histogram::print() {
	cout << str << endl << endl;
	cout << "총 알파벳 수 " << getAlphabetSize() << endl << endl;

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

int Histogram::getAlphabetSize() {
	int cnt = 0;
	for (int i = 0; i < str.length(); i++) {
		if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
			cnt++;
		}
	}
	return cnt;
}


void Histogram::countAlphabet() {
	for (int i = 0; i < str.length(); i++) {
		if (str[i] >= 'A' && str[i] <= 'Z') {
			int ind = str[i] - 'A';
			alphabet[ind]++;
		}
		if (str[i] >= 'a' && str[i] <= 'z'){
			int ind = str[i] - 'a';
			alphabet[ind]++;
		}
	}
}

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();

	return 0;
}


14번
소스 코드

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;

class Player {
	int card[3];
	string name;
public:
	Player() :Player("플레이어") { }
	Player(string name) { this->name = name; }
	string getName() { return name; }
	bool playGambling();
};
bool Player::playGambling() {
	for (int i = 0; i < 3; i++) {
		card[i] = rand() % 3;
		cout << "\t" << card[i];
	}
	for (int i = 0; i < 2; i++) {
		if (card[i] != card[i + 1]) {
			return false;
		}
	}
	return true;
}

class GamblingGame {
	Player player[2];
	bool isGameCompleted = false;
public:
	GamblingGame();
	void play();
};

GamblingGame::GamblingGame() {
	cout << "*****갬블링 게임을 시작합니다. *****" << endl;
	string name;
	cout << "첫번째 선수 이름>>";
	cin >> name;
	player[0] = Player(name);
	cout << "두번째 선수 이름>>";
	cin >> name;
	player[1] = Player(name);
	getchar();
}

void GamblingGame::play() {
	int i = 0;
	while (!isGameCompleted) {
		cout << player[i % 2].getName() << ":<Enter>";
		getchar();
		if (player[i % 2].playGambling()) {
			isGameCompleted = true;
			cout << "\t" << player[i % 2].getName() << "님 승리!!" << endl;
		}
		else {
			cout << "\t아쉽군요!" << endl;
		}
		i++;
	}
}

int main() {
	GamblingGame game;
	game.play();

	return 0;
}

모르는 문제 도움 출처 : https://mindorizip.tistory.com

profile
컴퓨터공학과에 재학중이며, 백엔드를 지향하고 있습니다. 많이 부족하지만 열심히 노력해서 실력을 갈고 닦겠습니다. 부족하고 틀린 부분이 있을 수도 있지만 이쁘게 봐주시면 감사하겠습니다. 틀린 부분은 댓글 남겨주시면 제가 따로 학습 및 자료를 찾아봐서 제 것으로 만들도록 하겠습니다. 귀중한 시간 방문해주셔서 감사합니다.

0개의 댓글