대학교 수업/C++ 프로그래밍

[C++] 명품 C++ 프로그래밍 7장 OpenChallenge

Jongung 2022. 6. 9. 17:05

히스토그램 클래스에 <<, ! 연산자 작성

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

class Histogram {
	int index;
	string str;
public:
	Histogram(string str) {
		this->str = str;
	}
	Histogram& operator << (string c) {
		str += c;
		return *this;
	}
	void operator !() {
		cout << str << endl;

		int alphabet[26] = {};
		int cnt = 0;
		for (int i = 0; i < str.length(); i++) {
			if (isalpha(str[i])) {
				cnt++;
			}
		}
		cout << "총 알파벳 수 : " << cnt<<endl;
		for (int i = 0; i < str.length(); i++) {
			if (isalpha(str[i])) {
				char temp = tolower(str[i]);
				alphabet[(int)(temp - 'a')]++;
			}
		}

		for (int i = 0; i < 26; i++) {
			cout << (char)('a' + i) << ": ";
			for (int j = 0; j < alphabet[i]; j++) {
				cout << "*";
			}
			cout << endl;
		}
	}
};

int main() {
	Histogram song("Wise men saym \nonly fools rush in But I can't help, \n");
	song << "falling" << "in love with you." << " - by";
	song << "k" << "i" << "t";
	!song;
}