c++ program translates english to morsecode ,but cant translate morsecode to english!!

----I dont receive any errors or warnings
----Im using visual studio 2019
----the program translates english to morse fine, but when trying to translate morse to english, the program just spits back out the morse that was suppose to be translated to english


code:
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#include <iostream>//headerfile
#include <fstream>//headerfile
#include <iomanip>//headerfile
#include <ctime>//headerfile
#include <string>//headerfile
#include <cctype>//headerfile

using namespace std;

class BST //binary search tree class
{
private://private class
	struct Node
	{
		string letter;//english string variable
		string code;//morsecode string variable
		Node* left;// points to left memory location in tree
		Node* right;//points to right memory location in tree
	};
	Node* root;//points root node memory location
public:// public class
	BST()
	{
		root = NULL;//empty tree
	}
	void Insert(Node*& r, string letter, string code)//insert english and morse string into tree
	{
		if (r == NULL)//if node is empty
		{
			r = new Node;//assigns r to new node
			r->letter = letter;//r accesses string letter
			r->left = r->right = NULL; r->code = code;
		}
		if (r->letter > letter) Insert(r->left, letter, code);//accesses the property of left node///
		if (r->letter < letter) Insert(r->right, letter, code);//accesses the property of right node////
	}
	void Insert(string letter, string code)//insert english and morse string into tree
	{
		Insert(root, letter, code);//insert english and morse string into root node
	}
	void DisplayPreOrder(Node* r)//display tree traversal
	{
		if (r != NULL)//if node is not empty
		{
			cout << r->letter << "\t";//display letter node
			DisplayInOrder(r->left);//display tree traversal
			DisplayInOrder(r->right);//display tree traversal
		}
	}
	void DisplayInOrder(Node* r)//display tree traversal
	{
		if (r != NULL)//if node is not empty
		{
			DisplayInOrder(r->left);//display tree traversal of left traversal
			cout << r->letter << "\t";
			DisplayInOrder(r->right);//display tree traversal of right traversal
		}
	}
	// Overrides DisplayInOrder(Node * )
	void DisplayInOrder()//display tree traversal functions
	{
		DisplayInOrder(root);//display tree traversal functions
	}
	void DisplayPreOrder()//display tree traversal functions
	{
		DisplayPreOrder(root);//display tree traversal functions
	}
	void DisplayPostOrder(Node* r)//display tree traversal functions
	{
		if (r != NULL)//if node is not empty
		{
			DisplayPostOrder(r->left);//display tree traversal of left traversal
			DisplayPostOrder(r->right);//display tree traversal of right traversal
			cout << r->letter << "\t";
		}
	}
	void Encode(char x)//function to encode morsecode string 
	{
		Node* r = SearchAndReturn(root, x);//points to value returned x 
		if (r != NULL) //if node is not empty
			cout << r->code;
		else cout << "Error.";//display error
	}
	void Decode(string x)//functiont to decode english string
	{
		Node* r = SearchAndReturnString(root, x);//search node r and return string
		if (r->code == x)
			cout << r->letter;
		else
			cout << r->code << " with x being " << x << endl;//displays the strings translated to english
		cout << "Error.";//display error to user
	}
	Node* SearchAndReturn(Node* r, char x)//function to search and retreive value in tree
	{
		if (r != NULL)//if node is not empty
		{
			if (r->letter[0] == x) { return r; }
			else if (r->letter[0] > x)
			{
				SearchAndReturn(r->left, x);//search and return left node
			}
			else
			{
				SearchAndReturn(r->right, x);//search and return right node
			}
		}
		else return NULL;//return empty
	}
	Node* SearchAndReturnString(Node* r, string x)//function to search and retreive value in tree
	{
		if (r != NULL)//if node is not empty
		{
			if (r->code == x)
			{
				cout << r->code << " matches " << x << endl; return r;
			}
			else if (r->code > x)
			{
				SearchAndReturnString(r->left, x);
			}//function to search and retreive value in tree
			else
			{
				SearchAndReturnString(r->right, x);
			}//function to search and retreive value in tree
		}
		else return NULL;//return empty
	}
};
struct alphaTree
{
	string letter;
	string code;
};
int main()
{
	time_t u;
	time(&u);
	cout << ctime(&u) << endl;//function to display current time
	BST t; string message; char* morseCode = new char; char ans;
	alphaTree array[27] = { {"E", ". "}, {"T", "- "}, {"I", ".. "}, {"A", ".- "}, {"N", "-. "}, {"M", "-- "},//tree containing character and their morsecode translation
	{"S", "... "}, {"U", "..- "}, {"R", ".-. "}, {"W", ".-- "}, {"D", "-.. "}, {"K", "-.- "},//tree containing character and their morsecode translation
	{"G", "--. "}, {"O", "--- "}, {"H", ".... "}, {"V", "...- "}, {"F", "..-. "}, {"L", ".-.. "},//tree containing character and their morsecode translation
	{"P", ".--. "}, {"J", ".--- "}, {"B", "-... "}, {"X", "-..- "},//tree containing character and their morsecode translation
	{"C", "-.-. "}, {"Y", "-.-- "}, {"Z", "--.. "}, {"Q", "--.- "}, {" ", "---- "} };//tree containing character and their morsecode translation
	t.Insert("0", "");
	for (int i = 0; i < 27; i++)//for loop for character insertions into tree
	{
		t.Insert(array[i].letter, array[i].code);//insert function into tree
	}
	do
	{
		cout << "Enter your message: ";//ask the user to enter their message to be decoded
		getline(cin, message);//extracts characters from string
		int len = message.length();//length method call of string length
		for (int i = 0; i < len; i++)//convert string to upper case for loop
		{
			message[i] = toupper(message[i]);//convert string to upper case for loop
			char c = message[i];
			if (c == ' ')
				cout << "/ ";
			t.Encode(c);//function to encode morsecode 
		}
		cout << endl;
		cout << "Enter your Morse code, separated by /, ended by *: ";//ask user to enter morsecode to be encoded
		cin.getline(morseCode, 100, '*');//extracts characters from string
		char* token = strtok(morseCode, "/");
		while (token != NULL)//while token is not empty
		{
			cout << endl << "Decoding: " << token << endl;
			string newCode = token;
			t.Decode(newCode);//decode function
			token = strtok(NULL, "/");
		}
		cout << "Continue: ";
		cin >> ans; cin.ignore(); cout << endl;
	} while (ans == 'y');
	return 0;
}

Last edited on
the code should be formatted correctly now, thx for the link
Look at what my compiler says about your code:


||=== Build: Debug in c++homework (compiler: gcc9-2) ===|
/main.cpp||In function ‘int main()’:|
/main.cpp|167|error: ‘strtok’ was not declared in this scope; did you mean ‘strtoq’?|
/main.cpp||In member function ‘BST::Node* BST::SearchAndReturn(BST::Node*, char)’:|
/main.cpp|109|warning: control reaches end of non-void function [-Wreturn-type]|
/main.cpp||In member function ‘BST::Node* BST::SearchAndReturnString(BST::Node*, std::string)’:|
/main.cpp|128|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 1 error(s), 2 warning(s) (0 minute(s), 0 second(s)) ===|


By the way why are you messing with C-string and the (IMO) horrible strtok() function? You seem to know about C++ strings so stick with them and use std::stringstream to process your string.

Why does DisplayPreOrder() call DisplayInOrder()? Typo?

Is your tree sorted by letter or by code? Insert() sorts it by letter. SearchAndReturnString() thinks it's sorted by code.

yup the DisplayPreOrder() call was a typo. The issue still exist after changing. When translating english to morse, it should sort by letter. morse code to english should search it by code
it should sort by letter. morse code to english should search it by code

If it's sorted by letter, then why does this code think it can search based on code?
1
2
3
4
5
6
7
8
			else if (r->code > x)
			{
				SearchAndReturnString(r->left, x);
			}//function to search and retreive value in tree
			else
			{
				SearchAndReturnString(r->right, x);
			}//function to search and retreive value in tree 


And second, did you read jlb's post? In particular:
/main.cpp|128|warning: control reaches end of non-void function [-Wreturn-type]|
More comments.

It took me a long time to get this code working. The code and data are poorly organized.

Ideally, the BST constructor should insert all the letter-to-string maps.

Why is Node::letter a string instead of a char?

Encode() should take a single character and return the morse code string rather than printing it out. Main should print the result. I'd return "?" if the character can't be encoded.

Also, call toupper() inside Encode() instead of within main().

Decode should take a string that represents the morse code of a single character and return that character. Return '?' if you can't decode it.

Why the funny '/' and '*' delimiters when decoding? Why not just spaces and a newline?

Here is main() with the changes I mentioned, except for moving the insertions to BST's constructor:
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
int
main()
{
    time_t u;
    time(&u);
    cout << ctime(&u) << endl;                   //function to display current time
    BST t;
    string message;
    char ans;
    alphaTree array[27] = { {'E', "."}, {'T', "-"}, {'I', ".."}, {'A', ".-"}, {'N', "-."}, {'M', "--"}, //tree containing cha\
racter and their morsecode translation
    {'S', "..."}, {'U', "..-"}, {'R', ".-."}, {'W', ".--"}, {'D', "-.."}, {'K', "-.-"}, //tree containing character and their\
 morsecode translation
    {'G', "--."}, {'O', "---"}, {'H', "...."}, {'V', "...-"}, {'F', "..-."}, {'L', ".-.."},     //tree containing character a\
nd their morsecode translation
    {'P', ".--."}, {'J', ".---"}, {'B', "-..."}, {'X', "-..-"}, //tree containing character and their morsecode translation
    {'C', "-.-."}, {'Y', "-.--"}, {'Z', "--.."}, {'Q', "--.-"}, {' ', "----"}
    };                                           //tree containing character and their morsecode translation
    for (int i = 0; i < 27; i++)                 //for loop for character insertions into tree
    {
        t.Insert(array[i].letter, array[i].code);       //insert function into tree
    }
    do {
        cout << "Enter your message: ";          //ask the user to enter their message to be decoded
        getline(cin, message);                   //extracts characters from string
        for (int i = 0; i < message.size(); i++)                 //convert string to upper case for loop
        {
            cout << t.Encode(message[i]) << ' ';
        }
        cout << endl;

        cout << "Enter your Morse code, separated by spaces: "; //ask user to enter morsecode to be encoded
        string morseCode;
        getline(cin, morseCode);                 //extracts characters from string
        istringstream is(morseCode);
        string token;
        while (is >> token) {
            cout << t.Decode(token);
        }
        cout << '\n';
        cout << "Continue: ";
        cin >> ans;
        cin.ignore();
        cout << endl;
    } while (ans == 'y');
    return 0;
}
I dont receive any errors, just 2 warnings: C26495

Do you honestly believe anyone here has memorised thousands of Microsoft message codes? If you want us to know what warning messages you're getting, then show us the actual messages.
I'm truly curious to know why my post was reported. If you reported it or think you know why, please say so, or send me a PM.
I dont receive any errors, just 2 warnings: C26495

Along with what was said about this by MikeyBoy above, what else do your messages say? They should point you to the line, and maybe even the position within that line where the error is detected.

Also just "Googling" the error number will probably show you a link to some Microsoft Documentation within the first five search links.

These are the 2 warnings i receive:

Severity Code Description Project File Line Suppression State
Warning C26495 Variable 'BST::Node::right' is uninitialized. Always initialize a member variable (type.6). ConsoleApplication15 C:\USERS\18168\SOURCE\REPOS\CONSOLEAPPLICATION15\CONSOLEAPPLICATION15\CONSOLEAPPLICATION15.CPP 20

and


Severity Code Description Project File Line Suppression State
Warning C26495 Variable 'BST::Node::left' is uninitialized. Always initialize a member variable (type.6). ConsoleApplication15 C:\USERS\18168\SOURCE\REPOS\CONSOLEAPPLICATION15\CONSOLEAPPLICATION15\CONSOLEAPPLICATION15.CPP 20

both warnings are line 20
Last edited on
Simple fix for the warning:
13
14
15
16
17
18
19
20
struct Node
	{
                // initializing struct data members using uniform initialization
		string letter;
		string code;
		Node* left  { nullptr };
		Node* right { nullptr };
	};

Now left and right have a value on creation, the warning should go away.

std::strings don't need to be initialized in the struct body because they are default initialized to be empty on creation.

Look at that last warning message:

Severity Code Description Project File Line Suppression State
Warning C26495 Variable 'BST::Node::left' is uninitialized. Always initialize a member variable (type.6). ConsoleApplication15 C:\USERS\18168\SOURCE\REPOS\CONSOLEAPPLICATION15\CONSOLEAPPLICATION15\CONSOLEAPPLICATION15.CPP 20


See that 20 at the end of the second line? That is the line number of the offending line.

By the way be aware that you appear to be using the Core Guidelines Checker so you will probably get more messages than from the compiler alone (this is probably a good thing). You really need to learn to read the messages your tools are providing and always treat warnings as errors (for now anyways).

Topic archived. No new replies allowed.