d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > English To Morse Code (and Vice Versa) > C++
12Next
Add Reply New Topic New Poll
Member
Posts: 89,702
Joined: Jul 14 2008
Gold: 165,885.69
Feb 28 2016 01:03am
Hi again!

My code is not finished, but heres a pretty good start to what I am trying to do

Code
#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>

using namespace std;

string texttomor (string, string[]);

int main()
{
char text[26] = {'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'};

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

string code, morsecode;
char choice; // ignore for now
char repeat = 'y' || 'Y'; // ignore for now
int lengthoftext=code.length();

{
cout << "Enter code to translate: " << endl;
getline(cin, code);
cout << "Text: " << code << endl;
cout << "Morse: " << texttomor(code, morse) << endl;
}
return 0;
}

string texttomor (string code, string morse[])
{
int codelength = code.length();
string spacesBetweenLetters = " ";
string spacesBetweenWords = " ";

for(int k=0; k<codelength; k++)
{
if(code[k]!= ' ')
code[k]=toupper(code[k]);
spacesBetweenLetters += morse[code[k] - 'A'];
spacesBetweenLetters+= " ";


if(code[k]==' ')

spacesBetweenWords+= morse[code[k]-'A'];
spacesBetweenWords+= " ";
}


return spacesBetweenLetters;
}


This compiles fine, but here is my issue:

When I input a single word, it converts it to morse code no problem.. but if I do two words with a space, it does a core dump.

I'm also in search of some help doing MORSE to ENGLISH... I've tried a few ways, but have been very unsuccessful, so any help is appreciated :)

*** For this project, I have to use cin.get... right now its getline, but I'm going to deal with that at some other point.

Also, I am trying to use C strings instead of C++ strings, so I'm still figuring all that shit out too :P

This post was edited by Rws on Feb 28 2016 01:04am
Member
Posts: 89,702
Joined: Jul 14 2008
Gold: 165,885.69
Feb 28 2016 02:33am
Just wanted to add.. each function has to be 15 or less lines (not including white space/comments)

I am turning this project in tomorrow night at MIDNIGHT

This post was edited by Rws on Feb 28 2016 02:52am
Member
Posts: 89,702
Joined: Jul 14 2008
Gold: 165,885.69
Feb 28 2016 04:48pm
I just got home, so I'll be checking this thread pretty often... if anybody has any suggestions, feel free to post or PM me. I also have skype, and would be happy to talk about it too.

Here are the requirements for the project:

http://classes.engr.oregonstate.edu/eecs/winter2016/cs161-001/assign/assign5.pdf
Member
Posts: 1,995
Joined: Jun 28 2006
Gold: 7.41
Feb 28 2016 06:28pm
Your code is segfaulting because you are trying to access a negative index in your morse array. The culprit is this statement:

Code
if(code[k]==' ')
spacesBetweenWords+= morse[code[k]-'A'];


code[k] is a space, which has an ascii value of 32. 'A' has an ascii value of 65. So you are attemping to access index -33. I don't think you should be attempting to convert a space to a morse code anyways.

As for your other question about morse to english, it would seem you should be able to do the same thing for english to morse but in reverse. You say you have tried some things unseccussfully, but what were those things?
Member
Posts: 89,702
Joined: Jul 14 2008
Gold: 165,885.69
Feb 28 2016 07:05pm
Quote (Minkomonster @ Feb 28 2016 04:28pm)
Your code is segfaulting because you are trying to access a negative index in your morse array. The culprit is this statement:

Code
if(code[k]==' ')
spacesBetweenWords+= morse[code[k]-'A'];


code[k] is a space, which has an ascii value of 32. 'A' has an ascii value of 65. So you are attemping to access index -33. I don't think you should be attempting to convert a space to a morse code anyways.

As for your other question about morse to english, it would seem you should be able to do the same thing for english to morse but in reverse. You say you have tried some things unseccussfully, but what were those things?


That makes sense. What should I do then to create spaces between the words then?

I got the morse to english code somewhat figured out, I'll post it up once I debug it more.
Member
Posts: 1,995
Joined: Jun 28 2006
Gold: 7.41
Feb 28 2016 07:24pm
My advice would be to tokenize your string into words using a space as a delimiter. You can then convert individual words into morse code and then concatenate the converted code into a single string by manually adding the spaces. Psuedocode would look like:

Code
//read english
string english = getLine();

//tokenize english by spaces using strtok or sstream
string[] words = tokenize();

//create a string to hold your morse code
string morseCode = "";

//convert every word
foreach(word in words)
{
string morse = englishToMorse(word);

morseCode += morse + " ";
}

//trim the trailing space from your morse code
morseCode = morseCode.trim();


morseCode now holds your inputted string converted to morse code. Doing it this way removes the need to check for spaces as every token you are converting is a single word.
Member
Posts: 89,702
Joined: Jul 14 2008
Gold: 165,885.69
Feb 28 2016 07:52pm
Here is a rough code for translating morse to text.....

Code
string morsetotext(string morse)
13 {
14 for (int j=0; j<25; j++)
15 {
16 if(morse == mor[j])
17 {
18 return text[j];
19 }
20
21 }
22
23 return ("Illegal character"); // Not recognised letter
24 }
25
26 int main()
27 {
28 string userInput;
29 cout << "Enter code to translate: " << endl;
30 getline(cin, userInput);
31
32 string create;
33
34 for (int i=0; i<userInput.size()+1; ++i)
35 {
36 if((userInput[i] == ' ' || i == userInput.size())){
37
38 string translated = morsetotext(create);
39 cout << translated;
40 create.clear();
41 }
42 else
43 {
44 create = create + (userInput[i]);
45 }
46 }
47 return 0;
48 }
Member
Posts: 89,702
Joined: Jul 14 2008
Gold: 165,885.69
Feb 28 2016 08:34pm
The problem is that I created the above code in another file, to practice Morse to Text.. if I were to implement this into my main one (the one in ORIGINAL post), it gets all messy and MAIN has more than 15 lines.

I'm trying really hard to figure this all out, but I'm definitely slipping.
Member
Posts: 1,995
Joined: Jun 28 2006
Gold: 7.41
Feb 28 2016 09:28pm
So here is a C# implementation of your morse code translater. You can see how the logic can be slimmed to the point hat the 15 LOC limit for the methods can be met.

Code

using System;
namespace MorseCoder
{
public class Program
{
private static string[] _morseCode = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};

static void Main(string[] args)
{
string english = Console.ReadLine();
string morseCode = EnglishToMorseCode(english);
Console.WriteLine(morseCode);
Console.WriteLine(MorseCodeToEnglish(morseCode));
Console.Read();
}

public static string[] TokenizeSentence(string sentence)
{
//in c++ you would use something like strtok or sstream
return sentence.Split(' ');
}

public static string EnglishToMorseCode(string englishText)
{
string[] words = TokenizeSentence(englishText);

string morseCode = "";
foreach(string word in words)
{
morseCode += EncodeWord(word) + " ";
}

return morseCode.Trim();
}

public static string MorseCodeToEnglish(string morseCode)
{
string[] codes = TokenizeSentence(morseCode);

string english = "";
foreach(string code in codes)
{
english += DecodeLetter(code);
}

return english;
}

private static string EncodeWord(string word)
{
word = word.ToUpper();

string code = "";
foreach (char letter in word)
{
code += _morseCode[letter - 'A'] + ' ';
}

return code.Trim();
}

private static char DecodeLetter(string code)
{
//this is a bit non-performant. Ideally this would be a lookup table for constant time search
for (int i = 0; i < _morseCode.Length; i++)
if (_morseCode[i].Equals(code))
return (char)(i + 'A');

throw new ArgumentException("Code not found");
}
}
}

Member
Posts: 89,702
Joined: Jul 14 2008
Gold: 165,885.69
Feb 28 2016 11:47pm
COMPILED

Code
#include <iostream>
2 #include <string>
3
4
5 using namespace std;
6
7 string engtomol (string, string[]);
8 string moltoeng (string, string[]);
9
10 int main ()
11 {
12 string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
13 string text, morsecode;
14 char choice;
15 char repeat='y';
16
17 while (repeat=='y')
18 {
19 cout << "Enter 1 to decode English to Morse\nEnter 2 to decode Morse code to English" << endl;
20 cin >> choice;
21
22 if (choice=='1')
23 {
24 cout << "Enter text to translate: ";
25 cin.get();
26 getline(cin,text);
27 // cout << "TEXT: " << text << endl;
28 cout << "MORSE CODE: " << engtomol(text, morse) << endl;
29 }
30 else if (choice=='2')
31 {
32 cout << "Enter your morsecode, space inbetween each letter. If multiple words, add 3 spaces after each word: ";
33 cin.get();
34 getline(cin,morsecode);
35 // cout << "MORSECODE: " << morsecode << endl;
36 cout << "TEXT: " << moltoeng (morsecode, morse) << endl;
37 }
38
39 cout << "Would you like to try again? Enter y to repeat. Enter any other key to exit. ";
40 cin >> repeat;
41 }

43 return 0;
44 }
45
46 string engtomol (string text, string morse[])
47 {
48 int textlength = text.length();
49 string morsevalue;
50 string spacesbtwletters= " ";
51 string spacesbtwwords = " ";//2 spaces because im going to add it with spacesbtwletters so that it will = 3
52 for (int k=0; k<textlength; k++)
53 {
54 if (text[k]!= ' ') //if the word(s) did not encounter a space
55 { text[k]=toupper(text[k]); //upper case letters and lower case letters are the same hence have the same appropriate morse code.
56 morsevalue = spacesbtwletters+= morse[text[k]-'A']+" "; // Subracting A finds the correct
57 }
58 if (text[k]==' ')
59 {
60 spacesbtwletters+=spacesbtwwords;//adds 3 spaces when there is a space between words
61 }
62 }
63 return morsevalue;
64 }
65
66 string moltoeng(string morsecode, string morse[])
67 {
68 string english[26] = {"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" };
69 string output = ""; //output for function
70 int index = 0;
71 while(index < morsecode.size())
72 {
73 //find current morse code
74 string letter = "";
75 int x = 0;
76 while(morsecode[index] == ' ')
77 {
78 x++;
79 index++;
80 if(x==3){
81 output+= ' ';
82 break;
83 }
84 }
85 while(morsecode[index] != ' ')
86 {
87 letter += morsecode[index++];
88 } //find this code in the morse alphabet
89 int position = 0;
90 for(position=0; position < 26; position++)
91 {
92 if(morse[position]==letter)
93 {
94 output+=english[position];
95 ++index; //to get rid of the space character.
96 break;
97 }
98 }
99 }
100 return output;
101 }






FOR THE ASSIGNMENT (which is due in less than 2 hours...) I need to convert C++ strings to C strings, and not use any of the functions in the library (such as length)

Any tips? If not, I will email my professor and ask for a day extension so I can go to office hours tomorrow and get TA help.
Go Back To Programming & Development Topic List
12Next
Add Reply New Topic New Poll