Jump to content

C - String to morse code using arrays

Go to solution Solved by Nineshadow,

@GR412

  7546796-morse-code-Stock-Photo.jpg

 

We're gonna make an array with these values. Actually , just for the alphabet (a through z). The rest don't really matter that much.

So this is our array of strings:

char *u[36] =  {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..","-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};

So we have the morse code representation of 'a' and 'A' in the first position of the array , and so on.                                                                         

Or you could use a hash map/dictionary(as it is called in Python).But since we're working with C , we don't exactly have that luxury.          

Then you read character by character and transform them into their respective morse code representation.

// str is a pointer to the morse representation of the character c , which is read into character by character from stdin
char *str, c;
//do while EOF isn't reached
do{

//set our string pointer to null every time we iterate
str = 0 // or NULL

//read a character from stdin into c. toupper() is there just to get rid of different upper-case and lower-case letters.
c = toupper(getc(stdin));

//if c is a letter of the english alphabet , get its specific representation from the array of morse code representations.
if(c>='A'&&c<='Z') str=u[c-'A'];
               
//if c is a number , then get its specific representation also stored in the morse code array , except after the letters.
if(c>='0'&&c<='9') str=u[c-'0'+26];
               
//check for different symbols which aren't stored in our original array , just because it would have been too hard that way
// here I'm checking for space , as an example
if(c==' ') str="/";
/*
check for more symbols
               .
               .
               .
               .
               .
*/
               
 //Print our morse code string if it exists
 if(str) printf("%s",str);
}while(c!=EOF)

.

Right so I'm back again with yet another programming question. This time I'm trying to create a program that converts an input string from the user into morse code.

 

The only thing I can really think of so far is to create two arrays to store both the users string and the morse code symbols. Apart from that I have no idea really. I struggle with iterations. I know how they work when I see them but i find it almost impossible too implement my own. Any help would be greatly appreciated.

 

And yes I know the gets function is a bad habit but i'm just trying to understand how to implment my own interations for now.

 

Here is the code i've thought of so far: (I'm not even sure if my for loop is useful for this)

 

EDIT: for some reason I can't set this code with C syntax highlighting.

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

int main()
{
	int i;
	char input[255], morse['o ---', '--- o o o', '--- o --- o', '--- o o', 'o', 
	                       'o o --- o', '--- --- o', 'o o o o', 'o o', 'o --- --- ---', 
						   '--- o ---', 'o --- o o', '--- ---', '--- o', '--- --- ---', 
						   'o --- --- o', '--- --- o ---', 'o --- o', 'o o o', '---', 
						   'o o ---', 'o o o ---', 'o --- ---', '--- o o ---', '--- o --- ---', 
						   '--- --- o o']
	
	printf("Enter your string: ");
	
	gets(string);
	
	for (i = 0; input[i] != '\0'; i++)
	{
		if ()
			      	
	}
					
	printf(" Your string in morse is: ");		
	
	return 0;
}

 

   
   
Link to comment
Share on other sites

Link to post
Share on other sites

18 minutes ago, GR412 said:

Right so I'm back again with yet another programming question. This time I'm trying to create a program that converts an input string from the user into morse code.

 

The only thing I can really think of so far is to create two arrays to store both the users string and the morse code symbols. Apart from that I have no idea really. I struggle with iterations. I know how they work when I see them but i find it almost impossible too implement my own. Any help would be greatly appreciated.

 

And yes I know the gets function is a bad habit but i'm just trying to understand how to implment my own interations for now.

 

Here is the code i've thought of so far: (I'm not even sure if my for loop is useful for this)

 

EDIT: for some reason I can't set this code with C syntax highlighting.


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

int main()
{
	int i;
	char input[255], morse['o ---', '--- o o o', '--- o --- o', '--- o o', 'o', 
	                         'o o --- o', '--- --- o', 'o o o o', 'o o', 'o --- --- ---', 
							 '--- o ---', 'o --- o o', '--- ---', '--- o', '--- --- ---', 
							 'o --- --- o', '--- --- o ---', 'o --- o', 'o o o', '---', 
							 'o o ---', 'o o o ---', 'o --- ---', '--- o o ---', '--- o --- ---', 
							 '--- --- o o']
	
	printf("Enter your string: ");
	
	gets(string);
	
	for (i = 0; input[i] != '\0'; i++)
	{
		if ()
			      	
	}
					
	printf(" Your string in morse is: ");		
	
	return 0;
}

 

Well I'm not going to write some code for you but here is how it should work : you should know the matches between the characters and their equivalent in morse code. Then to translate the string, you may should take advantage of the ASCII table and do something like :

 

for(i=0;i<string[i];i++)
                          printf('%c', morse[(string[i] - 'a');

This a just a rough idea. You should handle the capital letters for instance.

 

EDIT : it should be "%s" instead of "%c" since you are outputting strings.

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, IAmAndre said:

Well I'm not going to write some code for you but here is how it should work : you should know the matches between the characters and their equivalent in morse code. Then to translate the string, you may should take advantage of the ASCII table and do something like :

 


for(i=0;i<string[i];i++)
                          printf('%c', morse[(string[i] - 'a');

This a just a rough idea. You should handle the capital letters for instance.

 

EDIT : it should be "%s" instead of "%c" since you are outputting strings.

Right I'm gonna have to go away and think about this, i'm finding this really really hard. I've sat here for 4 hours trying. Iterations are so hard.

   
   
Link to comment
Share on other sites

Link to post
Share on other sites

#include <stdio.h>
#include <ctype.h>
char *u[36] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..","-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};
main(){
char*v;int x;char o;
do{
o = toupper(getc(stdin));v=0;if(o>=65&&o<=90)v=u[o-'A'];if(o>=48&&o<=57)v=u[o-'0'+26];if(o==46)v=".-.-.-";if(o==44)v="--..--";if(o==63)v="..--..";if(o==32)v="/";if(v)printf("%s ", v);} while (o != EOF);
}

 

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

15 hours ago, GR412 said:

Right I'm gonna have to go away and think about this, i'm finding this really really hard. I've sat here for 4 hours trying. Iterations are so hard.

I think it's quite easy actually, but you have to understand the principle. You loop through the characters in the string entered by the user, then you find their equivalent in your morse array. The index of each more equivalent is equal to letter (actually the ASCII code of the letter) - 'a'.

Link to comment
Share on other sites

Link to post
Share on other sites

On 11/02/2016 at 2:08 PM, IAmAndre said:

I think it's quite easy actually, but you have to understand the principle. You loop through the characters in the string entered by the user, then you find their equivalent in your morse array. The index of each more equivalent is equal to letter (actually the ASCII code of the letter) - 'a'.

This is the problem. I have the concept in my head but I have no idea how to write it in C. I know C's syntax up to this level, but I can't apply that knowledge of the syntax to problems such as this. I'm not sure what I'm going to do. This one question has been plaguing me for 3 weeks. When you say something like "find their equivalent in your morse array" I have no idea at all how to do that.

   
   
Link to comment
Share on other sites

Link to post
Share on other sites

On 10/02/2016 at 11:22 PM, Nineshadow said:

#include <stdio.h>
#include <ctype.h>
char *u[36] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..","-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};
main(){
char*v;int x;char o;
do{
o = toupper(getc(stdin));v=0;if(o>=65&&o<=90)v=u[o-'A'];if(o>=48&&o<=57)v=u[o-'0'+26];if(o==46)v=".-.-.-";if(o==44)v="--..--";if(o==63)v="..--..";if(o==32)v="/";if(v)printf("%s ", v);} while (o != EOF);
}

 

I don't understand that. I'd rather something a bit simpler.

   
   
Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, GR412 said:

I don't understand that. I'd rather something a bit simpler.

It is pretty simple. I just kinda obfuscated it.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

22 hours ago, GR412 said:

This is the problem. I have the concept in my head but I have no idea how to write it in C. I know C's syntax up to this level, but I can't apply that knowledge of the syntax to problems such as this. I'm not sure what I'm going to do. This one question has been plaguing me for 3 weeks. When you say something like "find their equivalent in your morse array" I have no idea at all how to do that.

OK you have two arrays, or just one. The most important array you should have is the one containing all the morse strings. I assume that each string has a matching alphabetical character, which means that the first character of your morse array should match the first character of the alphabet ("A"). Then one approach is to have another array containing all the letters of the alphabet, another one (the simpler approach I think) is to use the ASCII code : if the user enters "E", then you can calculate the index of the morse equivalent by subtracting the ASCII value of "A" to the ASCII value of "E". Does it make sense?

Link to comment
Share on other sites

Link to post
Share on other sites

We had to do this for an assignment. I am not sure how familiar you are with data structures, but we had to use binary search trees to store the morse code and english equivalent. The contents of the search tree are ordered based on their english lettering order, so you simply search the tree until you match your english letter, then you return the morse code equivalent which is stored at the same node

Link to comment
Share on other sites

Link to post
Share on other sites

32 minutes ago, Tuero said:

We had to do this for an assignment. I am not sure how familiar you are with data structures, but we had to use binary search trees to store the morse code and english equivalent. The contents of the search tree are ordered based on their english lettering order, so you simply search the tree until you match your english letter, then you return the morse code equivalent which is stored at the same node

Storing those in two arrays where letter 'a' in first array has same index as ".-" in second one is faster. Binary tree has logarithmic time where two arrays has const.  And it easier to implement.

Link to comment
Share on other sites

Link to post
Share on other sites

@GR412

  7546796-morse-code-Stock-Photo.jpg

 

We're gonna make an array with these values. Actually , just for the alphabet (a through z). The rest don't really matter that much.

So this is our array of strings:

char *u[36] =  {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..","-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};

So we have the morse code representation of 'a' and 'A' in the first position of the array , and so on.                                                                         

Or you could use a hash map/dictionary(as it is called in Python).But since we're working with C , we don't exactly have that luxury.          

Then you read character by character and transform them into their respective morse code representation.

// str is a pointer to the morse representation of the character c , which is read into character by character from stdin
char *str, c;
//do while EOF isn't reached
do{

//set our string pointer to null every time we iterate
str = 0 // or NULL

//read a character from stdin into c. toupper() is there just to get rid of different upper-case and lower-case letters.
c = toupper(getc(stdin));

//if c is a letter of the english alphabet , get its specific representation from the array of morse code representations.
if(c>='A'&&c<='Z') str=u[c-'A'];
               
//if c is a number , then get its specific representation also stored in the morse code array , except after the letters.
if(c>='0'&&c<='9') str=u[c-'0'+26];
               
//check for different symbols which aren't stored in our original array , just because it would have been too hard that way
// here I'm checking for space , as an example
if(c==' ') str="/";
/*
check for more symbols
               .
               .
               .
               .
               .
*/
               
 //Print our morse code string if it exists
 if(str) printf("%s",str);
}while(c!=EOF)

.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

Don't know C but here is a small script I wrote in python

 

def getCode(character):
    character = character.lower()
    code = ""
    if character == "a":
        code = ".-"
    elif character == "b":
        code = "-..."
    elif character == "c":
        code = "-.-."
    elif character == "d":
        code = "-.."
    elif character == "e":
        code = "."
    elif character == "f":
        code = "..-."
    elif character == "g":
        code = "--."
    elif character == "h":
        code = "...."
    elif character == "i":
        code = ".."
    elif character == "j":
        code = ".---"
    elif character == "k":
        code = "-.-"
    elif character == "l":
        code = ".-.."
    elif character == "m":
        code = "--"
    elif character == "n":
        code = "-."
    elif character == "o":
        code = "---"
    elif character == "p":
        code = ".--."
    elif character == "q":
        code = "--.-"
    elif character == "r":
        code = ".-."
    elif character == "s":
        code = "..."
    elif character == "t":
        code = "-"
    elif character == "u":
        code = "..-"
    elif character == "v":
        code = "...-"
    elif character == "w":
        code = ".--"
    elif character == "x":
        code = "-..-"
    elif character == "y":
        code = "-.---"
    elif character == "z":
        code = "--.."
    else:
        code = ""
    return code


running = True
while (running == True):    
    userInput = input("Please enter a phrase to convert to morse code or type e to quit: ")
    if (userInput == "e"):
        running = False
    else:
        morseCode = ""
        for i in userInput:
            if i != " ":
                morseCode += getCode(i) + " "
            else:
                morseCode += "| "

        print(morseCode + "\n")
Link to comment
Share on other sites

Link to post
Share on other sites

20 hours ago, Nineshadow said:

@GR412

  7546796-morse-code-Stock-Photo.jpg

 

We're gonna make an array with these values. Actually , just for the alphabet (a through z). The rest don't really matter that much.

So this is our array of strings:


char *u[36] =  {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..","-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};

So we have the morse code representation of 'a' and 'A' in the first position of the array , and so on.                                                                         

Or you could use a hash map/dictionary(as it is called in Python).But since we're working with C , we don't exactly have that luxury.          

Then you read character by character and transform them into their respective morse code representation.


// str is a pointer to the morse representation of the character c , which is read into character by character from stdin
char *str, c;
//do while EOF isn't reached
do{

//set our string pointer to null every time we iterate
str = 0 // or NULL

//read a character from stdin into c. toupper() is there just to get rid of different upper-case and lower-case letters.
c = toupper(getc(stdin));

//if c is a letter of the english alphabet , get its specific representation from the array of morse code representations.
if(c>='A'&&c<='Z') str=u[c-'A'];
               
//if c is a number , then get its specific representation also stored in the morse code array , except after the letters.
if(c>='0'&&c<='9') str=u[c-'0'+26];
               
//check for different symbols which aren't stored in our original array , just because it would have been too hard that way
// here I'm checking for space , as an example
if(c==' ') str="/";
/*
check for more symbols
               .
               .
               .
               .
               .
*/
               
 //Print our morse code string if it exists
 if(str) printf("%s",str);
}while(c!=EOF)

.

ahh ok i understand now, thanks.

   
   
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×