Channi Studies

[C++] (Program) String 응용 암호화 프로그램 (string::npos) 본문

C++/프로젝트 (Project)

[C++] (Program) String 응용 암호화 프로그램 (string::npos)

Chan Lee 2023. 12. 15. 17:17

코드 설명

c++ style string을 연습하기 위한 암호화 및 해독 코드입니다.

alphabet 과 key 문자열에 각각 암호화시킬 알파벳과 암호화 결과 알파벳을 저장해 놓고,

.find 메소드로 인덱스를 찾아서 변환하는 방식으로 진행됩니다.

 

중요한 점은 영어를 제외한 띄어쓰기, 특수문자와 같은 문자는 alphabet 문자열에 존재하지 않기 때문에,

find 메소드를 사용했을 시 오류가 발생합니다.

 

이를 방지하기 위해 string::npos와 동일한지를 확인합니다.

 

string::npos는 'find문으로 특정 문자(열)를 찾지 못했을 시' 반환됩니다.

예를 들어, string s1 = "Hello my name is Ricky." 라는 문자열에 대하여

s1.find("lemon"); 을 했을 시, s1 문자열에 "lemon" 문자열은 포함되어 있지 않기 때문에 string::npos를 반환합니다.

이 점만 인지하면 아주 쉽게 이해할 수 있는 코드입니다.

 


코드

#include <iostream>
#include <string>

using namespace std;

int main() {
    string message_input {};
    string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
    string key {"XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"};

    // 1. Ask the user to enter a secret message.
    cout << "Enter a secret message that you want to encrypt: ";
    getline(cin, message_input);    

    // 2. Encrypt the message using substitution cypher and display it.
    for (size_t index = 0; index < message_input.size(); index++){        
        if (alphabet.find(message_input[index]) == string::npos){
            continue;
        }
        message_input[index] = key.at(alphabet.find(message_input[index]));
    }
    cout << "\nEncrypting the message..." << endl;
    cout << "The secret message has encrypted to: " << message_input << endl;

    // 3. Decrypt the encrypted message again and display it.
    cout << "\nDecrypting the encrypted message..." << endl;
    for (size_t index = 0; index < message_input.size(); index++){
        if (alphabet.find(message_input[index]) == string::npos){
            continue;
        }
        message_input[index] = alphabet.at(key.find(message_input[index]));
    }

    cout << "The original message was: " << message_input << endl;
        
    cout << endl;
    return 0;
}

 


출력 결과

출력 결과