下面是使用C++编写的一个简单的莫斯编码和解码程序:

#include <iostream>
#include <map>
#include <string>

std::map<char, std::string> morseCode = {
    {'A', ".-"}, {'B', "-..."}, {'C', "-.-."}, {'D', "-.."}, {'E', "."},
    {'F', "..-."}, {'G', "--."}, {'H', "...."}, {'I', ".."}, {'J', ".---"},
    {'K', "-.-"}, {'L', ".-.."}, {'M', "--"}, {'N', "-."}, {'O', "---"},
    {'P', ".--."}, {'Q', "--.-"}, {'R', ".-."}, {'S', "..."}, {'T', "-"},
    {'U', "..-"}, {'V', "...-"}, {'W', ".--"}, {'X', "-..-"}, {'Y', "-.--"},
    {'Z', "--.."}, {'0', "-----"}, {'1', ".----"}, {'2', "..---"}, {'3', "...--"},
    {'4', "....-"}, {'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."},
    {'9', "----."}, {'.', ".-.-.-"}, {',', "--..--"}, {'?', "..--.."}, {'!', "-.-.--"},
    {'/', "-..-."}, {'(', "-.--."}, {')', "-.--.-"}, {'&', ".-..."}, {':', "---..."},
    {';', "-.-.-."}, {'=', "-...-"}, {'+', ".-.-."}, {'-', "-....-"}, {'_', "..--.-"},
    {'"', ".-..-."}, {'$', "...-..-"}, {'@', ".--.-."}, {' ', "/"}
};

std::map<std::string, char> reverseMorseCode;

void initializeReverseMorseCode() {
    for (const auto& pair : morseCode) {
        reverseMorseCode[pair.second] = pair.first;
    }
}

std::string encodeToMorse(const std::string& text) {
    std::string encodedText;
    for (const char& c : text) {
        if (morseCode.count(std::toupper(c)) > 0) {
            encodedText += morseCode[std::toupper(c)] + " ";
        }
    }
    return encodedText;
}

std::string decodeFromMorse(const std::string& morse) {
    std::string decodedText;
    std::string currentCode;
    for (const char& c : morse) {
        if (c == ' ') {
            if (reverseMorseCode.count(currentCode) > 0) {
                decodedText += reverseMorseCode[currentCode];
            }
            currentCode = "";
        } else {
            currentCode += c;
        }
    }
    if (reverseMorseCode.count(currentCode) > 0) {
        decodedText += reverseMorseCode[currentCode];
    }
    return decodedText;
}

int main() {
    initializeReverseMorseCode();

    std::string text;
    std::cout << "请输入要编码的文本: ";
    std::getline(std::cin, text);
    std::string encodedText = encodeToMorse(text);
    std::cout << "编码后的文本: " << encodedText << std::endl;

    std::string morse;
    std::cout << "请输入要解码的莫斯电码: ";
    std::getline(std::cin, morse);
    std::string decodedText = decodeFromMorse(morse);
    std::cout << "解码后的文本: " << decodedText << std::endl;

    return 0;
}

这个程序可以接受用户输入的文本,将其编码为莫斯电码,并将编码后的莫斯电码解码为原始文本。用户可以通过输入来测试莫斯编码和解码的功能

用c++做一个莫斯

原文地址: https://www.cveoy.top/t/topic/hXa9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录