간단한 C++ 예제입니다. 콘솔창에서 사용자에게 문자열을 ctrl+z 입력 전까지 입력받고, 그 입력 받은 문자열을 space bar 만큼 잘라서 몇 번 중복하는지 카운트하는 프로그램입니다. 특별히 들어간 문법이라고 한다면 struct, verctor, templet, 함수 정도 됩니다. 쉬운 예제이니 한 번 타이핑 하면서 이해하는 것도 공부에 도움이 됩니다.


CountWords.txt



 CountWords.cpp

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct WORD {
string str;
int count;
};

vector <WORD*> words;

int FindWords(const string& s);
void CountWords(const string& s);
void ShowWords();
void RemoveAll();

int main() {
cout << "문자열을 입력하세요. 입력을 마쳤으면 Ctrl+z 을 누르세요." << endl;
string buffer;
while( cin >> buffer)
CountWords(buffer);

ShowWords();
RemoveAll();

return 0;
}

void CountWords(const string& s) {
int index = FindWords(s);

if(index == -1) {
WORD *pWord = new WORD;
pWord->str = s;
pWord->count = 1;
words.push_back(pWord);
}

else {
words[index]->count++;
}
}

int FindWords(const string& s) {
for(int i = 0; i<words.size(); i++){
if(words[i]->str == s)
return i;
}
return -1;
}

void ShowWords() {
for(int i=0; i<words.size(); i++)
cout << words[i]->str << " : " << words[i]->count << "번" << endl;
}

void RemoveAll() {
for(int i=0; i<words.size(); i++)
delete words[i];
}



 - 실행 콘솔창





posted by 쪼재