|
|
[11장 연습문제]
// 1
// 11.h
// X
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
int main() {
string str;
int cnt = 0;
cout << "문자열 입력 >>";
getline(cin, str);
for(int i = 0; i < str.length(); i++)
if( str[i] == 'a' || str[i] == 'A') cnt++;
cout << "문자열 안의 a는 " << cnt << "개" << endl;
}
// 11_func.cpp
// X
// 2
// 11.h
// X
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
int main() {
char ch;
while (true) {
cin.ignore(100, ';');
ch = cin.get();
if (ch == EOF) break;
while (ch != '\n' && ch != EOF) {
cout << ch;
ch = cin.get();
}
cout << endl;
if (ch == EOF) break;
}
}
// 11_func.cpp
// X
// 3
// 11.h
// X
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
int main() {
char ch;
while (true) {
ch = cin.get();
if (ch == EOF) break;
if (ch == ';') {
cout << endl;
cin.ignore(100, '\n');
continue;
}
cout << ch;
}
}
// 11_func.cpp
// X
// 4
// 11.h
// X
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
int main() {
cout.setf(ios::left);
cout.width(15); cout << "Number";
cout.width(15); cout << "Square";
cout.width(15); cout << "Square Root" << endl;
cout.fill('_');
cout.precision(3);
for (int i = 0; i <= 45; i += 5) {
cout.width(15); cout << i;
cout.width(15); cout << i * i;
cout.width(15); cout << sqrt(i) << endl;
}
}
// 11_func.cpp
// X
// 5
// 11.h
// X
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
inline void print8(std::string data) {
std::cout.width(8); std::cout << data; }
int main() {
cout.setf(ios::left);
for (int k = 0; k < 3; k++) {
print8("dec"); print8("hex"); print8("char");
}
cout << endl;
for (int k = 0; k < 3; k++) {
print8("___"); print8("___"); print8("____");
}
cout << endl;
for (int i = 0; i <= 127; i++) {
print8(to_string(i));
cout.width(8); cout << hex << i;
if (i >= 32 && i <= 126) {
string s = { (char)i }; print8(s);
} else print8(".");
if (i % 3 == 2) cout << endl;
}
}
// 11_func.cpp
// X
// 6
// 11.h
#ifndef HEADER_11_HPP
#define HEADER_11_HPP
#include <string>
namespace header_11 {
class Circle {
std::string name;
int r;
public:
Circle(int r=1, std::string name="");
int getr();
friend std::istream& operator>>(std::istream& is, Circle& c);
friend std::ostream& operator<<(std::ostream& os, const Circle& c);
};
}
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
int main() {
Circle d, w;
cin >> d >> w;
cout << d << w << endl;
}
// 11_func.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
namespace header_11 {
Circle::Circle(int r, string name) {
this->r = r; this->name = name; }
int Circle::getr() { return r; }
istream& operator>>(istream& is, Circle& c) {
cout << "반지름과 이름 입력 >> ";
is >> c.r >> c.name; return is; }
ostream& operator<<(ostream& os, const Circle& c) {
os << "반지름 " << c.r << " " << c.name << endl;
return os; }
}
// 7
// 11.h
#ifndef HEADER_11_HPP
#define HEADER_11_HPP
#include <string>
namespace header_11 {
class Phone {
std::string name;
std::string telnum;
std::string add;
public:
Phone(std::string name="", std::string talnum="", std::string add="");
friend std::istream& operator>>(std::istream& is, Phone& c);
friend std::ostream& operator<<(std::ostream& os, const Phone& c);
};
}
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
int main() {
Phone girl, boy;
cin >> girl >> boy;
cout << girl << endl << boy << endl;
}
// 11_func.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
namespace header_11 {
Phone::Phone(string name, string telnum, string add) {
this->name = name; this->telnum = telnum; this->add = add; }
istream& operator>>(istream& is, Phone& c) {
cout << "이름: "; getline(is, c.name);
cout << "전화번호:"; getline(is, c.telnum);
cout << "주소: "; getline(is, c.add); return is; }
ostream& operator<<(ostream& os, const Phone& c) {
os << c.name << "," << c.telnum << "," << c.add;
return os; }
}
// 8
// 11.h
#ifndef HEADER_11_HPP
#define HEADER_11_HPP
#include <string>
namespace header_11 {
std::istream& prompt(std::istream& is);
}
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
int main() {
string pas;
while(true) {
cin >> prompt >> pas;
if(pas == "C++") {
cout << "login success!!" << endl; break;
} else {cout << "login fail. try again!!" << endl; }
}
}
// 11_func.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
namespace header_11 {
istream& prompt(istream& is) {
cout << "암호? "; return is; }
}
// 9
// 11.h
#ifndef HEADER_11_HPP
#define HEADER_11_HPP
#include <string>
namespace header_11 {
std::istream& pos(std::istream& is);
}
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
int main() {
int x, y;
cin >> pos >> x;
cin >> pos >> y;
cout << x << ',' << y << endl;
}
// 11_func.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
namespace header_11 {
istream& pos(istream& is) {
cout << "위치는? "; return is; }
}
// 10
// 11.h
#ifndef HEADER_11_HPP
#define HEADER_11_HPP
#include <string>
namespace header_11 {
class Coffeemachine {
int coffee = 3, sugar = 3, cream = 3, water = 3, cup = 3;
enum { NORMALCOF, SUGARCOF, BLACKCOF, FILL, EXIT };
void (Coffeemachine::*action)(); // 멤버함수 출력용 함수 포인터
void menu(); // 각 변수별 출력 포멧: 변수 이름 + 갯수 + 만큼 '*' + 줄바꿈 출력
// + 줄바꿈 출력 후 보통 커피:0, 설탕 커피:1, 블랙 커피:2, 채우기:3, 종료:4>> 출력 후 입력에 맞는 함수를 *action으로 호출
bool Coffeemachine::consume(int cf, int sg, int cr, int wt, int cp);
void normalcof();
void sugcof();
void blackcof();
void fill();
public:
void run(); // ***** 커피자판기 가동 ***** 출력 후 manu() 호출
};
}
// 11_main.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
using namespace header_11;
int main() {
Coffeemachine machine;
machine.run();
}
// 11_func.cpp
#include "11.hpp"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
namespace header_11 {
void Coffeemachine::run() {
cout << "***** 커피자판기 가동 *****" << endl;
menu();
}
void Coffeemachine::menu() {
void (Coffeemachine::*funcs[])() = {
&Coffeemachine::normalcof, &Coffeemachine::sugcof,
&Coffeemachine::blackcof, &Coffeemachine::fill };
int choice;
while (true) {
string names[] = { "Coffee", "Sugar ", "Cream ", "Water ", "Cup " };
int counts[] = { coffee, sugar, cream, water, cup };
for (int i = 0; i < 5; i++) {
cout << names[i] << " ";
for (int j = 0; j < counts[i]; j++) cout << '*';
cout << endl; }
cout << "\n보통 커피:0, 설탕 커피:1, 블랙 커피:2, 채우기:3, 종료:4>> ";
cin >> choice;
if (choice == EXIT) break;
if (choice >= NORMALCOF && choice <= FILL) {
action = funcs[choice];
(this->*action)();
}
cout << endl;
}
}
bool Coffeemachine::consume(int cf, int sg, int cr, int wt, int cp) {
if (coffee >= cf && sugar >= sg && cream >= cr && water >= wt && cup >= cp) {
coffee -= cf; sugar -= sg; cream -= cr; water -= wt; cup -= cp;
return true; }
cout << "재료가 부족합니다." << endl; return false;
}
void Coffeemachine::normalcof() {
if (consume(1, 1, 1, 1, 1)) cout << "보통 커피가 나왔습니다." << endl;
}
void Coffeemachine::sugcof() {
if (consume(1, 1, 0, 1, 1)) cout << "설탕 커피가 나왔습니다." << endl;
}
void Coffeemachine::blackcof() {
if (consume(1, 0, 0, 1, 1)) cout << "블랙 커피가 나왔습니다." << endl;
}
void Coffeemachine::fill() {
coffee = sugar = cream = water = cup = 10;
cout << "모든 재료를 10개로 채웠습니다." << endl;
}
}
// [11장 정리문제]
// 1) 스트림 버퍼가 무엇인가
// 스트림 버퍼는 프로그램과 입출력 장치의 사이에서 데이터를 일시적으로 저장하는 메모리상의 중간 매개체이다.
// 2) cin , cout 이 선언된 파일을 찾아서 그것의 정체를 자세히 설명하시오
// cin과 cout은 표준 입출력 스트림 헤더인 <iostream> 내부에 extern 키워드를 사용하여 선언되어 있고,
// C++ 표준 라이브러리의 런타임 라이브러리 파일 내부에 바이너리 형태로 구현되어 있다.
// 또한 iostream은 C++ 표준 라이브러리의 선언부를 담고 있는 헤더 파일으로, 연산자가 존재함을 컴파일러에게 알리는
설계도 역할을 한다.
// 3) 삽입연산자 (<<), 추출연산자 (>>) 함수는 어디에 선언되어 있는가
// cin(), cout()과 마찬가지로 iostream 안에 선언되고 C++ 표준 라이브러리의 런타임 라이브러리 파일 내부에 구현되어 있다.
// 4) cin , cout 이 입출력장치 키보드 모니터 와 통신하는 방식을 설명하시오
// 중간 매개체인 스트림 버퍼를 사용하며, 최종적으로는 운영체제의 시스템 콜을 통해 하드웨어와 데이터를 주고받는다.
// 5) 스트림버퍼를 사용하는 장점에 대해 설명하시오
// 매번 발생하는 시스템 콜 횟수를 줄여 입출력 성능을 최적화하고, 하드웨어와 프로그램 사이의 속도 차이를 조절하여 데이터 전송 효율을 극대화한다.
// 6) 삽입연산자 (<<), 추출연산자 의 반환형을 설명하시오
// 자기 자신인 스트림 객체의 참조자를 반환하여 이를 통해 여러 개의 데이터를 한 줄에 처리하는 연산자 체이닝을 사용할
수 있다.
// 7) cout << a << b << c << endl ; 에서 연산자함수가 리턴형이 참조형이어야 하는 이유를 설명하시오
// 반환된 객체가 다음 연산의 왼쪽 피연산자가 되어야 하는 연산자 체이닝을 구현하기 위해서이며 참조를 사용해야만 원본
스트림 객체의 상태를 유지하며 연속적인 입출력이 가능하기 때문이다.
// 8) endl 의 정체를 자세히 설명하시오 . 삽입연산자가 endl을 어떻게 처리하는지 자세히 설명하시오
// endl은 단순한 개행 문자가 아니라 개행 출력과 출력 버퍼 비우기를 동시에 수행하는 조정자 함수를 호출하는 함수
포인터이며 단순히 줄바꿈만 하는 '\n'에 비해 매번 시스템 콜을 발생시키므로 데이터가 많을 때 출력 성능을 크게 떨어뜨릴
수 있다.
// 또한 ostream 클래스 내부에 이러한 함수 포인터를 인자로 받는 operator<<가 정의되어 있어 사용자가 endl을 마치
데이터처럼 줄지어 쓸 수 있도록 설계되어 있다.
|
|
