Converting english to morse code

Pages: 12
Hello I have three questions: the first one is when I run my code and enter text for it when it returns its one letter short and as a result it doesn't give the correct morse code translation, i dont see where this problem is steaming from if you could just tell me the line so i can fix it i would be grateful.

The second is that while i have the mores code for the numbers with in the string mores[39] the computer doesn't recognize them and as a result crashes is there a way for me to fix this?

and finally my teacher doesn't want me to use string toMorse (string, string[]); but instead wants me to use string toMorse(char); for the function which doesn't really make sense to me as char would only allow for a single character wouldn't it so the final question is how would i use char instead of string string and still keep it to where i can enter a line of text and it would still out put a line of mores code and if a full line isn't possible how would i do it even with only the single character sorry this is an online class and as you can see im still very new to coding

If i don't message back right away its because i'm currently going to a funeral at 6:30 and won't be near my pc till after it but i will message back as soon as possible thank you for your time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 #include <iostream>
#include <string>
#include <cctype>
using namespace std;
string toMorse (string, string[]);

int main ()
{
    string morse[39] = {"--..--", ".-.-.-", "..--..","-----", ".----", "..---", "...--", "....-", ". ...", "-....", "--...", "---..", "----.", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
    string text;
 
        cout << "Please enter a character, word or phrase to translate from english to morse code \n";
        cin.get();
        getline(cin,text);
        cout << "Your text \n" << text << endl;
        cout << "Here it is in morse code \n " << toMorse(text, morse) << endl;
return 0;
}    



string toMorse (string text, string morse[])
{
    int textlength = text.length();
    string morseCodeValue;
    string sL= " ";
    string sW = "  ";
for (int index = 0; index < textlength; index++)
    {
        if (text[index]!= ' ')
        {   text[index]=toupper(text[index]);
            morseCodeValue=sL+=morse[text[index]-'A']+" ";
        }
        if (text[index]==' ')
        {
            sL+=sW;
        }
    } 
return morseCodeValue; 
}
That is not morse code.
Edit> Ignore that I see you didn't start with the alphabet.
Last edited on
it returns its one letter short
Remove line 13.

code for the numbers with in the string mores[39] the computer doesn't recognize them
You can determine what kind of letter you have:

http://www.cplusplus.com/reference/cctype/isalpha/?kw=isalpha
http://www.cplusplus.com/reference/cctype/isdigit/
http://www.cplusplus.com/reference/cctype/isspace/

I suggest to make seperate arrays for both types. That makes the calculation of the index easier.

but instead wants me to use string toMorse(char);
You can move line 9 inside the toMorse() function. If you should provide a single character only you need to move the loop on line 28 to main().
@coder777 Thank you for the quick reply and for the references the first one worked the words are no longer one letter short thank you. I looked at the references you gave for the second question and that just lead to even more confusion if cctype contains all of which is required why would it not work it seems like it should. and as for the last one would moving line 9 help what would be the point in doing that also if i was to move the loop to the main wouldn't that make the function pointless?? thank you for you time im just wondering.
Could you use a map? Say map<char,string>.

Then you could associate any text char cleanly with a morse-code string.
the best way probably is a map or even a vector.
I would think a vector of 3 bools as your base type put into a lookup table that ties back to the ascii table as a one to one lookup. Then a few constants, like the word STOP for end of sentence should be coded.
I don't think so the teacher is really adamant about it being string toMorse(char); so if anyone knows how to do it this way if you can can you show me how that small part would look Thank you.
I need something like the the answer that is given but i don't know how to use maps it looks simple enough but i just get a ton of errors if anyone could help with this by showing me my code in this format that would be much appreciated

(The Link to the code)
http://stackoverflow.com/questions/42176678/c-convert-ascii-to-morse-code
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>

using namespace std;

const int morse_size = 39;
const string morse[morse_size] =
{
    ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
    "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
    "..-","...-",".--","-..-","-.--","--..","-----",".----",
    "..---","...--","....-",".....","-....","--...","---..","----."
};
string toMorse (char);

int main ()
{
    
    string text, coded_text;
    
    cout << "Please enter a character, word or phrase to translate from english to morse code \n";
    
    getline(cin,text);
    cout << "Your text \n" << text << endl;
    
    for(int i = 0; i < text.length(); i++ )
    {
        coded_text += toMorse(text[i]) + ' ';
    }
    
    cout << "Here it is in morse code \n " << coded_text << endl;
    
    return 0;
}


string toMorse (char aCharacter)
{
    return  morse[ tolower(aCharacter) - 'a'];;
}
Oh that is wonder full thaknk you for the reply but for me at least it still crashes when a number or special character is entered. is there any way to fix this??
closed account (48T7M4Gy)
If it crashes then you are probably trying to convert a character (or special) that puts the index = aCharacter - 'a' out of the range of the morse[] array. The index value is either negative or greater than the morse_size

So, you can check for that before the conversion is done, as part of the toMorse function. Maybe output a '?' if the conversion fails.

Keep in mind also that strictly speaking Morse code is restricted to just a small set of characters.
Last edited on
You will have to add punctuation etc. to the map, but I don't know what those characters are in morse. If it doesn't find a character in the map it should simply ignore it and move on.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <map>
using namespace std;

map<char,string> m;
map<char,string>::iterator it;

//===========================

void setMap()                          // set the mapping from characters to code
{
   m['A'] = m['a'] = ".-";
   m['B'] = m['b'] = "-...";
   m['C'] = m['c'] = "-.-.";
   m['D'] = m['d'] = "-..";
   m['E'] = m['e'] = ".";
   m['F'] = m['f'] = "..-.";
   m['G'] = m['g'] = "--.";
   m['H'] = m['h'] = "....";
   m['I'] = m['i'] = "..";
   m['J'] = m['j'] = ".---";
   m['K'] = m['k'] = "-.-";
   m['L'] = m['l'] = ".-..";
   m['M'] = m['m'] = "--";
   m['N'] = m['n'] = "-.";
   m['O'] = m['o'] = "---";
   m['P'] = m['p'] = ".--.";
   m['Q'] = m['q'] = "--.-";
   m['R'] = m['r'] = ".-.";
   m['S'] = m['s'] = "...";
   m['T'] = m['t'] = "-";
   m['U'] = m['u'] = "..-";
   m['V'] = m['v'] = "...-";
   m['W'] = m['w'] = ".--";
   m['X'] = m['x'] = "-..-";
   m['Y'] = m['y'] = "-.--";
   m['Z'] = m['z'] = "--..";
   m['1'] = ".----";
   m['2'] = "..---";
   m['3'] = "...--";
   m['4'] = "....-";
   m['5'] = ".....";
   m['6'] = "-....";
   m['7'] = "--...";
   m['8'] = "---..";
   m['9'] = "----.";
   m['0'] = "-----";
   m[' '] = " ";
}

//===========================

string encode( string text )           // turn text into morse code
{
   char SPACE = ' ';
   string result;

   for ( int i = 0; i < text.size(); i++ )                      // loop through the text character by character
   {
      it = m.find( text[i] );                                   // iterator to the relevant character (if in map)
      if ( it != m.end() ) result += it->second + SPACE;        // if in map, add to morse code, otherwise do nothing
   }
   return result;
}

//===========================

int main()
{
   string line;

   setMap();
// for ( it = m.begin(); it != m.end(); it++ ) cout << it->first << " " << it->second << endl;   // check, if needed

   cout << "Input a line of text: ";
   getline( cin, line );
   cout << encode( line );
}

closed account (48T7M4Gy)
http://www.cplusplus.com/forum/beginner/192939/2/#msg930525

Just add any special or extra characters to the two arrays that drive the maps in this.
Last edited on
While i would love to use maps because I've been studying up on them and it seems that they work really well like your above code but the teacher is set on using string toMorse (char); like i said in the original can anyone see why from this code below it crashes when i enter a number or special character because i do have it and the table i am looking at does have them in mores. like your number nine in mores is ----. and when you enter that in your code you get the correct awnser but when it is entered in the code below it doesnt give me the correct awnser so is there anyway to change the below code so that is accepts numbers at the least???

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>

using namespace std;

const int morse_size = 39;
const string morse[morse_size] =
{
    ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
    "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
    "..-","...-",".--","-..-","-.--","--..","-----",".----",
    "..---","...--","....-",".....","-....","--...","---..","----."
};
string toMorse (char);

int main ()
{
    
    string text, coded_text;
    
    cout << "Please enter a character, word or phrase to translate from english to morse code \n";
    
    getline(cin,text);
    cout << "Your text \n" << text << endl;
    
    for(int i = 0; i < text.length(); i++ )
    {
        coded_text += toMorse(text[i]) + ' ';
    }
    
    cout << "Here it is in morse code \n " << coded_text << endl;
    
    return 0;
}


string toMorse (char aCharacter)
{
    return  morse[ tolower(aCharacter) - 'a'];;
}
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <string>

using namespace std;

const int morse_size = 122;
const int numerals = 10;
const int alpha = 26;

const string code[numerals + alpha] =
{
    "-----",".----", "..---","...--","....-",".....","-....","--...","---..","----.",
    
    ".-","-...","-.-.","-..",".","..-.","--.","....","..",".---",
    "-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
    "..-","...-",".--","-..-","-.--","--.."
};

string morse[morse_size];
string toMorse (char);

int main ()
{
    for(int i = 0; i < morse_size; i++)
        morse[i] = "???";

    morse[32] = " ";

    for(int i = 0; i < numerals; i++)
        morse[i + 48] = code[i];
    
    for(int i = 0; i < alpha; i++)
        morse[i + 97] = code[i + numerals];
    
    string text = "", coded_text = "";
    
    cout << "Please enter a character, word or phrase to translate from english to morse code \n";
    
    getline(cin,text);
    cout << "Your text \n" << text << endl;
    
    for(int i = 0; i < text.length(); i++ )
    {
        coded_text += toMorse(text[i]) + ' ';
    }
    
    cout << "Here it is in morse code \n " << coded_text << endl;
    
    return 0;
}


string toMorse (char aCharacter)
{
    return  morse[ tolower(aCharacter) ];
}
Last edited on
closed account (48T7M4Gy)
@OP a 1000 pardons. There was a logical blooper but it's fixed. It should be self explanatory from my code and you can work it out yourself easily with three hints:

1. I re-arranged the morse strings in lines 10-17 to simplify what happens later on.
2. I mapped (via arrays and not the banned <maps> ) the code to the ASCII table.
3. tolower function is there in order to ??? - (you can work out why ... :) )

Please enter a character, word or phrase to translate from english to morse code 
123 abC
Your text 
123 abC
Here it is in morse code 
 .---- ..--- ...--  .- -... -.-. 
Program ended with exit code: 0


Please enter a character, word or phrase to translate from english to morse code 
0123 abcABCxyzXYZ
Your text 
0123 abcABCxyzXYZ
Here it is in morse code 
 ----- .---- ..--- ...--  .- -... -.-. .- -... -.-. -..- -.-- --.. -..- -.-- --.. 
Program ended with exit code: 0


Last edited on
Not trying to say this for people to stop posting because i'm sure other people will want to know but honestly i just don't know what to do with the maps i studied up on it yesterday by myself but i got no where with it i may need to ask my teach but every time i ask him a question he says "this is something you need to solve yourself" which i understand but trying to learn c++ when your teacher dosen't help with nearly anything sucks i mean im still trying to figure this out even though the date pasted on Friday to turn it in so honestly this is just for me because i feel this is fun but i have no idea how to use maps so while i appreciate the help i think at this point im calling it quits ill have to go to the schools learning lab and hope there is someone that knows what there doing (because last time i went i had to help the other student that was there to teach also in his first semester how to input validate and make it into a function so yea i really dont have high hopes for them) and can help me learn how to do this for i can just know how to do it thanks @kemort you have been a huge help but your code seems a little to advanced for me like im really new to this and just haven't learn enough to understand what you did i just wish my code worked.

one think i didn't understand is why 122 for the mores_size, i didnt know you could do the numerals + alpha in the string code then separate them with in the array, i don't even understand your first 3 for loops and the numbers you put with in

as for you questions
1. for the first hunt im assuming you literally swamped the alphas and the numerical but how that would make it more efficient later i don't know
2. again i have no idea really how to map so im at a lost there i can only assume you mean something like what @lastchance did but even then something like that would still need to utilize a string and a char so that it would convert with no errors so as for mapping im lost
3. and yes the tolower is there to make capital letters into lower case letters but i fail to see how this as a hint from what im seeing it looks correct to me

thank you guys for your time but im sure with what i turned in i received a failing grade because it didnt accept numbers or special characters if you have anything to add or want to help others with this because im sure this will help someone in the futur please do im still going to see if anyone adds to this becuse i would still like to know thank you for all for your help it was great but because he wants it a certain way i am at a loss.
closed account (48T7M4Gy)
@ The KingGamer117

I understand. Forget about <maps> until you cover them in class. They were a red herring and you weren't interested anyway because of the constraints you are under from your teacher.

Actually my code is very simple believe it or not ... When you get time look up ASCII. Each character has a position in the ASCII table and can be represented by a number. For the number zero char '0' is 48, char 122 is 'z' and all I did was make an array of 122 (+1) elements to store the morse codes against 0-9 then a-z.

If I know a character in the userText I know it's index number and therefore the morse code.

Because I only put the morse codes in for 0-9 and a-z and not A-Z I use tolower. Simple.

I started by initializing (swamping) the array with "???" so any character outside the one's there are codes for will be converted to "???". Simple. It doesn't make it more efficient but tells you the conversion, but only the default value is being used. Note that you can change "???" to a message "No direct conversion available"

I put in morse[32] = ' ' to allow for spaces. Simple also.

Cheers
Last edited on
So then what was the logical blooper?? and thank you i am going to wait to use mapping until i cover them a lot better, also i will definitely look it all up i feel it will be good to know for future endeavors. when you say you swapped the array (im guessing the const string code[numerals + alpha] ) did you mean literally and if so would that not break the code later on because you call mores size before hand. also i understand that there is a logical error but the the code instantly crash for you on start up (im not at the point where i can see errors with out the compiler the another teacher from another class said he could help me with that but I have yet to attend his class) the reason i ask is because i dont get errors but the code crashes when compiled. again thank you for your time.
closed account (48T7M4Gy)
The blooper was I didn't build the morse array properly so in the first version it didn't make sense and caused the program to give the wrong result.
Last edited on
Pages: 12