Morse Code
Text to Morse Code Converter in C++

Morse Code is a method of transmitting text via a series of sounds or dots and dashes and is named after Samuel Morse, the inventor of the telegraph. Turning text into Morse Code in C++ involves mostly implementing for loops and arrays.

Libraries to Include

The first thing you should do is include the following libraries at the top of your code.

#include <string>
#include <iostream>
#include <algorithm>

Defining the Functions

After including the needed libraries declare the following function, it’ll contain the entirety of the program.

void texttomorse();

The Int Main Function

After defining all the functions you’ll need, create the int main function. The only thing that it needs to contain is a call to the text to Morse function.

int main()
{
 texttomorse();
}

Creating the Arrays

Directly below the main function begin defining the text to Morse function. The first thing that you need to do is create two arrays, one of them should be a char that contains every letter of the alphabet and numbers 0-9. The other should be a string that contains the morse code translation of each letter of the alphabet and numbers 0-9.

char text[36] = {'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',
 '1','2','3','4','5','6','7','8', '9','0' };

 std::string morse[36] = {".-","-...","-.-.","-..",".","..-","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",
 ".----","..---","...--","....-",".....","-....","--....","---..","----.","-----"};

It is very important that each character in the char array is at the same position as its translation. This is because later on when your actually translating phrases you’ll be taking the position of each text character in its array and printing the morse code that is at the same position in the morse array.

Getting User Input

Next define the string that will hold the phrase the user wants translated and prompt them for it. To actually get the user input you need to use std::getline instead of the normal std::cin. This is because the latter stops at the first white space it encounters while the former will grab the whole line in-putted regardless of white space. There is no need for any error checking as any invalid characters will just be skipped during translation.

std::string phrase;
int input;

std::cout << "Enter the Text You Wish to Translate into Morse Code.\n";
std::getline(std::cin,phrase);

Before you can do the translation you’ll need to make sure every character held in the string is upper case. This is extremely important because otherwise the translator will only turn uppercase letters into morse code and ignore everything in upper case. To do this use the std::transform object from the algorithm library and use ::toupper to convert the string into all upper case.

std::transform(phrase.begin(), phrase.end(), phrase.begin(), ::toupper);

Translating from Text to Morse Code

The first thing that you should do is create a for statement that iterates through every character of the text.

 std::cout << "Your Entered Text in Morse Code:\n";

 for (int i = 0; i<phrase.length(); ++i)
 {

Directly after that write another for loop within the first one. This one will count up from 0 to 36, this is because there are 36 characters in each array and it needs check if the current character being iterated through matches any of them.

for (int counter = 0; counter < 36; counter++)
 {

Next create an if statement inside the second for loop. This should check if the current character being iterated through matches any character in the text array. If so then it should print the morse code that exists at the corresponding position in the morse array to the screen. When working this loop should print the morse code equivalent of every valid character in the phrase to the screen.

 if (phrase.at(i) == text[counter])
 {
 std::cout << morse[counter];
 soundplayer(morse[counter]);
 }

Finally just simply add a prompt asking the user if they wish to continue using the program or exit. If they choose to replay the program just call the text to morse function again and if they exit allow the text to morse function to finish and then the program will close as it reaches the end of the main function. Be sure to also include a while statement that checks for any invalid input, keeping the user trapped in it until they input a correct value.

std::cout << "\nWould You Like to Translate more Text into Morse Code (1) Or Exit the Program (2)?\n"; std::cin >> input;
 std::cin.ignore();

 while (input!=1&&input!=2)
 {
 std::cout <<"Invalid Input, Please Try Again\n"; std::cin.clear(); std::cin.ignore(256, '\n'); std::cin >> input;
 std::cin.ignore();
 }

 if(input=1)
 {
 texttomorse();
 }

 else if(input=2)
 {

 }

}

Adding Sound (In Windows Only)

If you’re running on a windows operating system you can also make the program play out the morse code sounds as it prints to the screen. To do this you will first want to go back and include the windows.h library and define these additional three functions.

#include <windows.h>

void dot();
void dash();
void soundplayer(std::string x)

After this you will want to go into the text to morse function and call the soundplayer function that you defined and pass morse[counter] as its argument. This will cause the corresponding sound to play as each morse character is outputted to the screen.

if (phrase.at(i) == text[counter])
 {
 std::cout << morse[counter];
 soundplayer(morse[counter]);
 }

Next you should define the dot() and dash() functions. These will implement the Beep() function from the windows.h library to create the sounds of morse code dots and dashes.

Beep() takes two int arguments. The first is how loud the sound played will be in hertz and the second argument is how long the sound will play in milliseconds. Both should dot and dash should be set to the same sound level and dash should last 3 times as long as dot.

void dot()
{
 Beep(900,100);
}

void dash()
{
 Beep(900,300);
}

Lastly you need to create the soundplayer function that you called on earlier on in the program. It takes one argument, string x which is of course the piece of morse code that it will be playing. In the function create a series of if statements and else if statements, one for each morse character. In them have the corresponding dots and dashes be played out.

void soundplayer(std::string x)
{
 if (x==".-")
 {
 dot();
 dash();
 }
 else if (x=="-...")
 {
 dash();
 dot();
 dot();
 dot();
 }
 else if (x=="-.-.")
 {
 dash();
 dot();
 dash();
 dot();
 }

For the sake of brevity I’m not going to put all 36 control statements here but this should give you a good idea of how each one needs to be set up.

Further Suggestions

Some extra things you can add to your program are: a function to reverse the process, translations for symbols and other alphabets like Cryllic, sound that will work on any operating system, and the ability to save translations to a text document.

Good Luck!

Download the above source code here.

If you have any comments or questions contact me at nick@crumbsofcode.com