반응형

Open Challenge> 아래< 5-1>을 참고하여 영문 텍스트, 숫자, 몇 개의 특수 문자로 구성되는 텍스트를 모스 부호로 변환하는 프로그램을 작성하라. 모스 부호는 전보를 쳐서 통신하는 시절에 사용된 유명한 코딩 시스템이다. 각 모스 코드들은 하나의 빈칸으로 분리되고, 영문 한 워드가 모스 워드로 변환되면 워드들은 3개의 빈칸으로 분리된다. 실행 예는 다음과 같다. 영문 텍스트를 입력받아 모스 부호로 변환하여 출력하고, 변환이 잘 되었는지 확인하기 위해 다시 모스 부호를 영문 텍스트로 변환하여 원문을 출력한 사례이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <algorithm>
#include <string>
 
using namespace std;
 
class Morse{
private:
    string alphabet[26]; //알파벳의 모스 부호 저장
    string digit[10]; //숫자의 모스 부호 저장
    string slash, question, comma, period, plus, equal; //특수 문자의 모스 부호 저장
public:
    Morse(); //alphabet[], digit[] 배열 및 특수 문자의 모스 부호 초기화
    void text2Morse(string text, string& morse); //영문 텍스트를 모스 부호로 변환
    bool morse2Text(string morse, string& text); //모스 부호를 영문텍스트로 변환
};
Morse::Morse(){
    string Malphabet[26]=".-""-...""-.-.""-.."".","..-.""--.""...."".."".---",
                   "-.-"".-..""--""-.""---",".--.""--.-"".-.""...""-",
                   "..-""...-"".--""-..-""-.--""--.."};
    string Mdigit[10]={"-----"".----""..---""...--""....-"".....""-....""--...""---..""----." };
    slash= "-..-.";    question= "..--..";    comma= "--..--";
    period= ".-.-.-";  plus= ".-.-.";     equal= "-...-"//모스 특수문자 초기화
    int i;
    for(i=0;i<26;i++){alphabet[i]=Malphabet[i];} //모스 알파벳 초기화
    for(i=0;i<10;i++){digit[i]=Mdigit[i];} //모스 숫자 초기화
}
void Morse::text2Morse(string text, string& morse){
    transform(text.begin(),text.end(),text.begin(),tolower); // 입력한 문자열을 전부 소문자로 바꾼다.
    for(int i=0;i<text.length();i++){
        if(text[i]>=97&&text[i]<=122){morse=morse+alphabet[text[i]-97]+" ";} //해당 인덱스가 알파벳일 경우 해당 모스 부호 삽입
        else if(text[i]==' '){morse+="   ";} //해당 인덱스가 공백문자 일경우 공백문자 3개 입력
        else if(text[i]>=48&&text[i]<=57){morse=morse+digit[text[i]-48]+" ";} //해당 인덱스가 숫자 일경우 해당 모스 부호 삽입
        else if(text[i]=='/'){morse=morse+slash+" ";}
        else if(text[i]=='?'){morse=morse+question+" ";}
        else if(text[i]==','){morse=morse+comma+" ";}
        else if(text[i]=='.'){morse=morse+period+" ";}
        else if(text[i]=='+'){morse=morse+plus+" ";}
        else if(text[i]=='='){morse=morse+equal+" ";} //해당 인덱스가 특수문자 일경우 해당 모스 부호 삽입
    }
}
bool Morse::morse2Text(string morse, string& text){
    string regen; //다시 읽을 수 있게 복원한 것을 넣을 스트링
    string sub; // 공백 문자 단위로 자름
    int i;
    int startindex=0//문자를 찾기 시작할 첫번째 index
    int blankindex=-1//공백문자의 index
    int swch=1//모스부호가 무엇인지 검사하는데 사용할 플래그
    while(1){
        swch=1//플래그는 루프 돌때마다 1로 ON
        startindex=blankindex+1//찾기 시작할 인덱스는 공백 인덱스 더하기 1
        blankindex=morse.find(" ",blankindex+1); //전에 찾았던 것을 또 찾으면 안되니 더하기 1을해서 공백문자를 찾는다.
        sub=morse.substr(startindex,blankindex-startindex); // 공백 문자를 제외한 무언가를 나타내는 모스부호 부분만 자른다.
        for(i=0;i<26;i++){
            if(alphabet[i]==sub)
                {regen+=(char)(97+i);
            swch=0;break;}    //알파벳일 경우 변환하여 regen에 더하고 플래그 OFF 후 루프 탈출
        }
        if(swch==1){
            for(i=0;i<10;i++){
                if(digit[i]==sub)
                {regen+=(char)(48+i);
                swch=0;break;}
            } //숫자일 경우 변환하여 regen에 더하고 플래그 OFF 후 루프 탈출
        }
        if(swch==1){
            if(sub==slash){regen+="/";}
            else if(sub==question){regen+="?";}
            else if(sub==comma){regen+=",";}
            else if(sub==period){regen+=".";}
            else if(sub==plus){regen+="+";}
            else if(sub==equal){regen+="=";}
        } //특수문자일 경우 regen에 더한다. 
 
        if(blankindex==morse.length()-1){break;} //여기서 검사하는 이유는 인덱스가 맨 마지막일때 +1,+2,+3 을 검사하면 오류가 나기 때문이다.
        if((morse[blankindex+1]==' ')&&(morse[blankindex+2]==' ')&&(morse[blankindex+3]==' ')){
            regen+=" ";     cout<<regen<<endl//제대로 이어졌나 확인.
            blankindex+=3//공백문자가 연달아 3개 있으면 실제에서는 공백문자 하나를 뜻한다. 이를 검사하기 위함.
        }
        }
    if(regen==text) return true//새로 만든 문자열과 원래 문자열이 같으면 true리턴
    else return false//아니면 false 리턴
}
int main(void){
    Morse m;
    string english;
    string morse;
    cout<<"아래에 영문 텍스트를 입력하세요. 모스 부호로 바꿉니다."<<endl;
    getline(cin,english,'\n'); //개행문자 나올 때까지 문자열 받는다
    m.text2Morse(english,morse); //모스부호로 전환
    cout<<morse<<endl;
    cout<<"모스 부호를 다시 영문 텍스트로 바꿉니다."<<endl;
    if(m.morse2Text(morse,english)) //다시 읽을 수 있는 텍스트로 전환
        cout<<english<<endl//만약 같으면 원래 문자열 출력
    else
        cout<<"오류 발생"<<endl//다르면 오류발생 출력
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

virtual 함수  (0) 2017.11.23
operator overloading  (0) 2017.11.14
Book 클래스  (1) 2017.11.09
Accumulator 클래스  (0) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
반응형

4.10> 영문자로 구성된 텍스트에 대해 각 알파벳에 해당하는 문자가 몇 개인지 출력하는 히스토그램 클래스 Histogram을 만들어보자. 대문자는 모두 소문자로 변환하여 처리한다. Histogram 클래스를 활용하는 사례와 실행 결과는 다음과 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <algorithm> //transform 함수 사용 위함
#include <string>
 
using namespace std;
 
class Histogram{
private:
    string s; //스트링 저장용
public:
    Histogram(string s){(this->s)+=s;} //생성자는 멤버스트링 s에 매개스트링 s를 더한다.
    void put(string s){(this->s)+=s;} //멤버스트링 s에 매개스트링 s를 더한다.
    void putc(char c){(this->s)=s+c;} //멤버스트링 s에 매개 캐릭터 c를 더한다.
    void print(){
        cout<<s<<endl//소문자화 하기전 출력
        transform(s.begin(),s.end(),s.begin(),tolower); //스트링 s를 전부 소문자화 시킴
        cout<<s<<endl//소문자화 한 후 출력
        for(int i=0;i<26;i++){ //알파벳이 26자라서 26번 돌린다.
            int count=0//알파벳 몇번 나왔나 셀 때 사용할 변수
            for(int k=0;k<s.size();k++){ //스트링 전부 순회
                if(s[k]==(i+97)) //아스키코드 97이 'a'라서 97~97+26 은 'a'~'z'를 의미한다. s의 각 문자를 'a'~'z'와 비교
                    count++//만약 s[k]가 i+97과 같으면 count 증가
            }
            cout<<(char)(i+97)<<" ("<<count<<")    :    "//출력
 
            for(int j=0;j<count;j++//count 수만큼 별 출력
                {cout<<"*";}
            cout<<endl//한줄 내린다.
        }
    }
};
 
int main(void){
    Histogram elvisHisto("Wise men say, only fools rush in But I can't help, ");
    elvisHisto.put("falling in love with you");
    elvisHisto.putc('-');
    elvisHisto.put("Elvis Presley");
    elvisHisto.print();
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

변수와 포인터와 참조  (0) 2017.11.08
float와 double  (0) 2017.11.05
Circle, CircleManager 클래스  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03

+ Recent posts