본문 바로가기

언어/C++

4장 10번 - 문장 알파벳 히스토그램 만들기

#include <iostream>
#include <string>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

class Histogram{
	string his;
	int len;
	int count[26];
public:
	Histogram(string h){
		his=h+"\n";
		len=0;
		
		for(int i=0; i<h.size(); i++){
			if(isalpha(his.at(i))) len++;
		}
		for(int i=0; i<26; i++){
			count[i]=0;
		}
	}
	void put(string h);
	void putc(char h);
	void print();
};

void Histogram ::put(string h){
	
	this->his+=h;
	for(int i=0; i<h.size();i++)
	{
		if(isalpha(h.at(i))) len++;
	}
	
}


void Histogram ::putc(char h){
	
	this->his+=h;
	if(isalpha(h)) len++;
}

void Histogram::print() {
	cout << his << endl << endl << "총 알파벳 수 " << len << endl << endl;
	
	char temp;
	for(int i=0; i<his.size();i ++){
		temp=tolower(his.at(i));
		count[temp-97]++;
	}
	
	for(int i=0; i<26; i++){
		printf("%c %d \t" ,97+i, count[i]);
		for(int j=0; j<count[i]; j++){
			cout << "*";
		}
		cout <<endl;	
	}	
}

int main(int argc, char** argv) {
	
	Histogram histo("falling in love with him");
	histo.put("I love you");
	histo.putc('-');
	histo.put("thank you");
	histo.print();
	return 0;
}