Search
Duplicate
🔢

4장. 실습문제

생성일
2022/03/25 02:14
태그
C++
1.
string 클래스를 이용하여 빈칸을 포함하는 문자열을 입력받고, 문자열에서 소문자가 각각 몇 개 있는지 출력하는 프로그램을 작성하시오.
#include <iostream> #include <string> using namespace std; void strCol() { // find를 사용하는 방법 string sen; int i = 0; cout << "문자열 입력> "; getline(cin, sen); int counts['z' - 'a' + 1] = {0,}; for (char c = 'a'; c <= 'z'; c++) { int index = 0; while(true) { index = sen.find(c, index); if (index == -1) break; // 못찾았으면 break else counts[c - 'a']++; index++; } } for (int c = 'a'; c <= 'z'; c++) { if (counts[c - 'a'] != 0) cout << (char)c << " : " << counts[c - 'a'] << endl; } } void strCol2() { string sen; int counts2['z' - 'a' + 1] = {0,}; for (int i = 0; i <= sen.length(); i++) { char c = sen[i]; if (c > 'a' && c <= 'z') { //소문자 판별 counts2[c - 'a']++; //카운트 증가 } for (int c = 'a'; c <= 'z'; c++) { if (counts2[c - 'a'] != 0) cout << (char)c << " : " << counts2[c - 'a'] << endl; } } int main() { strCol(); strCol2(); }
C++
복사
2.
다음과 같이 원을 추상화한 Circle 클래스가 있다. 사용자로부터 다음과 같이 원의 개수를 입력받고, 원의 개수 만큼 반지름을 입력받고 면적이 100보다 큰 원의 개수를 출력하는 프로그램을 작성하라. 단 원의 개수에 따라 동적으로 배열을 할당받아서 각 원의 정보를 저장해야한다.
main.cpp
#include <iostream> #include <string> #include "pr.h" using namespace std; void op() { cout << "원의 개수 >> "; int num, radius; cin >> num; Circle *pArray = new Circle[num]; // n 개의 circle 배열 생성 for (int i = 0; i < num; i++) { cout << "원 " << i << "의 반지름 >> "; cin >> radius; pArray[i].setRadius(radius); // 각 circle 객체를 반지름으로 초기화 } int count = 0; Circle *p = pArray; for (int i = 0; i < num; i++) { if (p->getArea() >= 100 && p->getArea() <= 200) count++; p++; } cout << "면적이 100보다 큰 원은 " << count << "개입니다." << endl; delete [] pArray; } int main() { op(); }
C++
복사
3.
다음은 커피자판기로 작동하는 프로그램을 만들기 위해 필요한 두 클래스이다. 이 클래스들을 사용해 아래와 같이 실행되도록 main() 함수와 CoffeeVendingMachine, Container 를 완성하라. 만일 커피, 물, 설탕 중 잔량이 하나라도 부족해 커피를 제공할 수 없는 경우 “원료가 부족합니다.” 를 출력하라. 또한 각 클래스를 별도의 파일로 작성하시오.
#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(); bool checkInputError(); 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() >= 1) { 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() >= 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; } bool CoffeeVendingMachine::checkInputError() { if(cin.fail()) { // cin 입력에 문제가 있는 경우 cin.clear(); // flag 리셋 cin.ignore(100, '\n'); // 버퍼리셋 cout << "입력 오류" << endl; return true; } else return false; } 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; }
C++
복사
1.
red, green, blue
#include <iostream> #include <cstdlib> 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->show(); p++; } }
C++
복사
2.
정수 공간 5개를 배열로 동적 할당 받고, 정수를 5개 입력받아 평균을 구하고 출력한뒤 배열을 소멸시키도록 main() 함수를 작성하라
#include <iostream> using namespace std; int main() { double ans = 0; int* p = new int[5]; cout << "정수 5개 입력>> "; for (int i = 0; i < 5; i++) { cin >> p[i]; ans += p[i]; } cout << "평균 " << ans / 5; delete [] p; }
C++
복사
3.
(1) 문자열에서 ‘a’ 를 찾기 위해 string 클래스의 멤버 at() 나 []를 이용하여 작성
#include <iostream> using namespace std; int main() { string s; cout << "문자열 입력>> "; getline(cin, s, '\n'); int count = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == 'a') count++; } cout << "문자 a는 " << count << "개 있습니다."; }
C++
복사
(2) string find() 사용
#include <iostream> using namespace std; string s; int count, idx; void fun(int x) { idx = s.find('a', x); if (idx != -1) { count++; fun(idx + 1); } else return; } int main() { string s; cout << "문자열 입력>> "; getline(cin, s, '\n'); fun(0); cout << "문자 a는 " << count << "개 있습니다."; }
C++
복사
5.
영문 한 줄 입력받고 글자 하나만 랜덤하게 수정 출력
#include <iostream> using namespace std; int main() { string s; srand((unsigned)time(0)); while(1) { cout << "아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)\n>>"; getline(cin, s, '\n'); if (s == "exit") break; int n = rand() % (s.length()); s[n] = rand() % 26 + 'a'; // 'a' ~ 'z' 까지 랜덤으로 생성 cout << s << endl; } }
C++
복사
12.
기보드에서 원 개수 입력받고, 그 개수만큼 원의 이름과 반지름을 입력
#include <iostream> using namespace std; class Circle { int radius; string name; public: void setCircle(string name, int radius); double getArea(); string getName(); }; class CircleManager { Circle *p; int size; int radius; string name; public: CircleManager(int size); ~CircleManager(); void searchByName(); void searchByArea(); }; 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; } CircleManager::CircleManager(int size) { 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() { cout << "검색하고자 하는 원의 이름 >> "; cin >> name; for (int i = 0; i < size; i++) { if (name == p[i].getName()) { cout << p[i].getName() << "의 면적은 " << p[i].getArea() << endl; } } } void CircleManager::searchByArea() { cout << "최소 면적을 정수로 입력하세요 >> "; cin >> radius; cout << radius << "보다 큰 원을 검색합니다.\n"; for (int i = 0; i < size; i++) { if (radius < p[i].getArea()) { cout << p[i].getName() << "의 면적은 " << p[i].getArea() << ", "; } } } int main() { int size; cout << "원의 개수 >> "; cin >> size; CircleManager CM(size); CM.searchByName(); CM.searchByArea(); }
C++
복사