以下是一个用C语言实现的摩斯电码转换程序的示例代码:
#include <stdio.h>
#include <string.h>
void morseToText(char* morseCode) {
char* codes[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
"-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--",
"....-", ".....", "-....", "--...", "---..", "----.", "-----"};
char* letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char* token = strtok(morseCode, " ");
while (token != NULL) {
int i;
for (i = 0; i < sizeof(codes) / sizeof(codes[0]); i++) {
if (strcmp(token, codes[i]) == 0) {
printf("%c", letters[i]);
break;
}
}
token = strtok(NULL, " ");
}
printf("\n");
}
void textToMorse(char* text) {
char* codes[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
"-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--",
"....-", ".....", "-....", "--...", "---..", "----.", "-----"};
char* letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int i;
for (i = 0; i < strlen(text); i++) {
char c = toupper(text[i]);
if (c >= 'A' && c <= 'Z') {
printf("%s ", codes[c - 'A']);
} else if (c >= '0' && c <= '9') {
printf("%s ", codes[26 + c - '0']);
}
}
printf("\n");
}
int main() {
char input[100];
char choice;
printf("Enter 'M' to convert from Morse code to text, 'T' to convert from text to Morse code: ");
scanf("%c", &choice);
if (choice == 'M' || choice == 'm') {
printf("Enter Morse code: ");
scanf("%s", input);
morseToText(input);
} else if (choice == 'T' || choice == 't') {
printf("Enter text: ");
scanf("%s", input);
textToMorse(input);
} else {
printf("Invalid input.\n");
}
return 0;
}
这个程序可以根据用户的选择将摩斯电码转换为文本,或将文本转换为摩斯电码。用户需要输入相应的选择和待转换的电码或文本。程序将输出转换结果。