반응형

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
반응형

5.7> 클래스 Accumulator add() 함수를 통해 계속 값을 누적하는 클래스로서, 다음과 같이 선언된다. Accumulator 클래스를 구현하라.


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
#include <iostream>
 
using namespace std;
 
class Accumulator{
private:
    int value;
public:
    Accumulator(int value);//매개 변수 value 로 멤버 value 초기화
    Accumulator& add(int n); //vlaue에 n을 더해 값 누적
    int get(); //누적된 값 value 리턴
};
Accumulator::Accumulator(int value){
    this->value=value; //value 값 이니셜라이징
}
Accumulator& Accumulator::add(int n){
    value+=n;
    return *this//리턴타입이 참조이다. this는 포인터이므로 역참조 연산자를 통해
                //참조를 리턴할 수 있다.
}
int Accumulator::get(){
    return value; //총더해진 값을 리턴
}
 
int main(void){
    Accumulator acc(10); //초기값 10
    acc.add(5).add(6).add(7); //5,6,7을 차례로 더한다
    cout<<acc.get(); //최종 더해진 값 리턴 (즉 28)
    return 0;
}
 
cs




반응형

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

모스 부호  (0) 2017.11.09
Book 클래스  (1) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
using namespace std;
 
int main(void){
 
    int a[2]={6,10};
    int *p=a; //포인터 p는 배열a의 첫번째 원소를 가리키는 포인터
    int &r=*a; //r은 a의 첫번째 원소의 참조
    int &r2=r; //r2는 r의 참조 (참조의 참조)
 
    cout<<a[0]<<endl//6
    cout<<*p<<endl//6
    cout<<r<<endl//6
    cout<<r+1<<endl//6+1=7
    cout<<a<<endl//주소
    cout<<&r<<endl//첫번째 원소의 주소 =a
    cout<<*(&r)<<endl//레퍼런스 주소의 역참조 = 6
    cout<<*(&r+1)<<endl//레퍼런스 주소에 1을 더한것의 역참조 = 10(2번째 원소)
    cout<<r2<<endl//r2는 r을 가리키므로 6
}
cs


포인터는 주소가 담기는 메모리가 할당 된다.

레퍼런스는 메모리 상의 특정 공간을 차지하는 것이 아니라 컴파일 시에

원래 레퍼런스가 참조하던 변수의 *(주소값)으로 대체되는 것이다.







반응형

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

MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03

+ Recent posts