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

 


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. 다음은 커피자판기로 작동하는 프로그램을 만들기 위해 필요한 두 클래스이다.

 

 

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

#define SIZE 3

struct menu {
	char name[20];
	int price;
};

struct menu m[3] = { "에스프레소", 2000, "아메리카노", 2300, "카푸치노", 2500 };

void print_menu();
int check_order(int count);
int get_order_price(char* name, int count);
void print_order(int price);

int main() {
	int total_price = 0;
	char name[20];
	int count, order_price;

	print_menu();

	while (total_price < 20000) {
		cout << "주문>> ";
		cin >> name >> count;
		
		if (!check_order(count)) {
			cout << "잘못된 수량입니다. 다시 주문하세요" << endl;
			continue;
		}
		order_price = get_order_price(name, count);
		if (order_price == 0) {
			cout << "메뉴에 없는 주문입니다. 다시 주문하세요" << endl;
			continue;
		}
		print_order(order_price);
		total_price += order_price;
	}
	cout << "오늘 " << total_price << "원을 판매하여 카페를 닫습니다. 내일 봐요~~~" << endl;
}

void print_menu() {
	for (int i = 0; i < SIZE; i++) {
		cout << m[i].name << " " << m[i].price << "원";
		if (i < SIZE - 1)
			cout << ", ";
	}
	cout << "입니다." << endl;
}

int check_order(int count) {
	if (count <= 0)
		return 0;
	return 1;
}

int get_order_price(char* name, int count) {
	for (int i = 0; i < SIZE; i++) {
		if (strcmp(name, m[i].name) == 0) {
			return count * m[i].price;
		}
	}
	return 0;
}


void print_order(int price) {
	cout << price << "원입니다. 맛있게 드세요" << endl;
}

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

1) 책에서 권장하는 방식

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

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int divi(int a, int b) {
    if (b == 0) return -999;
    return a / b;
}
int rem(int a, int b) {
    if (b == 0) return -999;
    return a % b;
}

int main() {
	int (*f[5])(int, int) = { add, sub, mul, divi, rem };
    char input[100];
    char* tok[3];
	int num1, num2, cal, result;

    while (true) {
        cout << "? ";
        cin.getline(input, sizeof(input), '\n');

		tok[0] = strtok(input, " ");
		tok[1] = strtok(NULL, " ");
		tok[2] = strtok(NULL, " ");
        num1 = atoi(tok[0]);
        num2 = atoi(tok[2]);

		switch (*tok[1]) {
		case '+':
			cal = 0; break;
		case '-':
			cal = 1; break;
		case '*':
			cal = 2; break;
		case '/':
			cal = 3; break;
		case'%':
			cal = 4; break;
		default:
			cout << "잘못된 수식을 입력했습니다.\n";
			continue;
		}
		result = f[cal](num1, num2);
		if (result == -999) {
			cout << "잘못된 수식을 입력했습니다.\n";
			continue;
		}
		cout << num1 << " " << *tok[1] << " " << num2 << " = " << result << endl;
	}
}

 

2) 내 맘대로 작성한 코드

#include <iostream>
using namespace std;

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }
int divi(int a, int b) { 
	if (b == 0) return -999;
	return a / b; }
int rem(int a, int b) { 
	if (b == 0) return -999;
	return a % b; }


int main() {
	int (*f[5])(int, int) = { add, sub, mul, divi, rem };
	int num1, num2, cal, result;
	char ch;
	
	while (1) {
		cout << "? ";
		cin >> num1 >> ch >> num2;

		switch (ch) {
		case '+':
			cal = 0; break;
		case '-':
			cal = 1; break;
		case '*':
			cal = 2; break;
		case '/':
			cal = 3; break;
		case'%':
			cal = 4; break;
		default:
			cout << "잘못된 수식을 입력했습니다.\n";
			continue;
		}
		result = f[cal](num1, num2);
		if (result == -999) {
			cout << "잘못된 수식을 입력했습니다.\n";
			continue;
		}
		cout << num1 << " " << ch << " " << num2 << " = " << result << endl;
 	}
}

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