用c++写完整的摩斯密码
时间: 2024-11-08 10:22:02 浏览: 21
在C++中编写一个完整的摩尔斯密码编码器和解码器可以分为两个部分:编码函数和解码函数。下面是一个简单的示例,包括了将字母转换成摩尔斯密码和从摩尔斯密码恢复字母的功能。
```cpp
#include <iostream>
#include <map>
#include <string>
std::string morse_code_table[26] = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...",
"-", "..-", "...-", ".--", "-..-", "-.--"
};
// 编码函数:将字母转为摩尔斯码
std::string encode_morse(const std::string &word) {
std::string result;
for (char c : word) {
if (isalpha(c)) {
result += morse_code_table[c - 'A'] + " ";
}
}
return result;
}
// 解码函数:将摩尔斯码还原为字母
std::string decode_morse(const std::string &morse) {
std::string decoded_word;
size_t i = 0;
while (i < morse.length()) {
std::string segment;
while (i < morse.length() && morse[i] != ' ') {
segment += morse[i];
++i;
}
decoded_word += segment == "." ? 'A' : segment == "-" ? 'B' : ' ';
i += morse[i - 1] != ' ' ? 3 : 2; // 空格间隔
}
return decoded_word;
}
int main() {
std::string input_word("Hello");
std::cout << "Original Word: " << input_word << "\n";
std::string encoded_morse = encode_morse(input_word);
std::cout << "Encoded Morse Code: " << encoded_morse << "\n";
std::string decoded_word = decode_morse(encoded_morse);
std::cout << "Decoded Word: " << decoded_word << "\n";
return 0;
}
```
阅读全文