Hello, i'm a noob C programmer, learning it at university. We have been given an assessment which i need to complete asap. I have figured out the solution to the porgram (almost) but need some assistace. I have a Java and VB background and i cannot seem to get my head around C & pointers!! i've been working on this problem for about 3 hours now. and i cant think any more. hence i cannot progress any further!!

Take a look at this.

#include "stdafx.h"
#include "stdio.h"
#include "ctype.h"
#include "string.h"

void encode(char *ch);
char alph[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* morsecode is an array of pointers to char. It is initialized
* so that each element points to a string literal with
* the ascii representation of each char of the array alph[]
*/

char *morsecode[] = { /* an array of pointers to char */
        ".- "  , "-..." , "-.-." , "-.."  , "."    ,    /* a-e */
        "..-." , "--."  , "...." , ".."   , ".---" ,    /* f-j */
        "-.-"  , ".-.." , "--"   , "-."   , "---"  ,    /* k-o */
        ".--." , "--.-" , ".-."  , "..."  , "-"    ,    /* p-t */
        "..-"  , "...-" , ".--"  , "-..-" , "-.--" ,    /* u-y */
        "--.." ,                                        /* z   */
};


	int main() {

		char *ch; 
		printf("please enter char to convert to morse: ");
		scanf_s("%s", &ch);
		encode(ch);
		return 0;
	}

	

	void encode(char *ch){   
		size_t i, j;   
		for ( i = 0; ch[i]; ++i )   {   
			for ( j = 0; j < sizeof ch; ++j )      {   
				if ( morsecode[(unsigned short)toupper(*ch) - alph[0]] )         {   
	
					printf("%c", morsecode);           
					break;       
				}     
			}  
		}  
		putchar('\n');
	}

i have to follow set criteria and code the solution using the arrays above. my method works fine. IT WORKS FINE for decoding one acharacter. But i need it to decode the whole string...
I'm having difficulty in looping through the entered string and returning the morse code.
please assist.

Member Avatar for iamthwee

The code you have written isn't standard c.

yes. We're being taught ANSI C first. tehn moving onto C++.. this assignment is being coded by the requirements of the lecturer. i was given the array, and i must implement my solution arounf it. The object is to have a program which converts a user input AND is able to read from a file and coverts that to morse code.
As you can see.. i'm stuck on the loop for the string.

Member Avatar for iamthwee
#include <stdio.h>
#include <ctype.h>
#include <string.h>

void encode ( char ch );
char alph[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* morsecode is an array of pointers to char. It is initialized
* so that each element points to a string literal with
* the ascii representation of each char of the array alph[]
*/

char *morsecode[] =
  { /* an array of pointers to char */
    ".- "  , "-..." , "-.-." , "-.."  , "."    ,    /* a-e */
    "..-." , "--."  , "...." , ".."   , ".---" ,    /* f-j */
    "-.-"  , ".-.." , "--"   , "-."   , "---"  ,    /* k-o */
    ".--." , "--.-" , ".-."  , "..."  , "-"    ,    /* p-t */
    "..-"  , "...-" , ".--"  , "-..-" , "-.--" ,    /* u-y */
    "--.." ,                                        /* z   */
  }; 
int main(void)
{
  char ch;
  printf ( "please enter char to convert to morse: " );
  scanf ( "%c", &ch );
  encode ( ch );
  getchar();
  getchar();
} 

void encode ( char ch )
{
  size_t i, j;
  for ( i = 0; i < 26; ++i )
  {
      if ( ch == alph[i])
      {
        printf ( "%s", morsecode[i] );
        break;
      } 
  }
  putchar ( '\n' );
}
Member Avatar for iamthwee

Untested.

Member Avatar for iamthwee

well?

hmm thanks for the solution. deosnt print anything out though! loool!... i can see what i was trying to do wrong.
hmm. i have not used getchar() before. .... this isnt returning anything to the console. i dont think morsecode is correct.? that said. im in no state to be right.

confused like shit at the moment.

Member Avatar for iamthwee
#include "stdafx.h"
#include "stdio.h"
#include "ctype.h"
#include "string.h"

void encode ( char ch );
char alph[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* morsecode is an array of pointers to char. It is initialized
* so that each element points to a string literal with
* the ascii representation of each char of the array alph[]
*/

char *morsecode[] =
  { /* an array of pointers to char */
    ".- "  , "-..." , "-.-." , "-.."  , "."    ,    /* a-e */
    "..-." , "--."  , "...." , ".."   , ".---" ,    /* f-j */
    "-.-"  , ".-.." , "--"   , "-."   , "---"  ,    /* k-o */
    ".--." , "--.-" , ".-."  , "..."  , "-"    ,    /* p-t */
    "..-"  , "...-" , ".--"  , "-..-" , "-.--" ,    /* u-y */
    "--.." ,                                        /* z   */
  }; 
int main(void)
{
  char ch;
  printf ( "please enter char to convert to morse: " );
  scanf_s ( "%c", &ch );
  encode ( toupper(ch) );
  return 0;
} 

void encode ( char ch )
{
  size_t i, j;
  for ( i = 0; i < 26; ++i )
  {
      if ( ch == alph[i])
      {
        printf ( "%s", morsecode[i] );
        break;
      } 
  }
  putchar ( '\n' );
}

And now?

nada. still not returning anything after the user input
hmm
printf ( "please enter char to convert to morse: " );
scanf_s ( "%c", &ch );

this should be
printf ( "please enter string to convert to morse: " );
scanf_s ( "%s", &ch );

the object is to encode the entrie string to morse one char at a time?

Member Avatar for iamthwee

what are you typing in?

ok at runtime, if i enter "hello" in the console. the program should return "morse: .... . .-.. .-.. ---"currently it deosnt return anything. just ends.

Member Avatar for iamthwee

And this one...

void encode ( char ch );
char alph[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* morsecode is an array of pointers to char. It is initialized
* so that each element points to a string literal with
* the ascii representation of each char of the array alph[]
*/

char *morsecode[] =
  { /* an array of pointers to char */
    ".- "  , "-..." , "-.-." , "-.."  , "."    ,    /* a-e */
    "..-." , "--."  , "...." , ".."   , ".---" ,    /* f-j */
    "-.-"  , ".-.." , "--"   , "-."   , "---"  ,    /* k-o */
    ".--." , "--.-" , ".-."  , "..."  , "-"    ,    /* p-t */
    "..-"  , "...-" , ".--"  , "-..-" , "-.--" ,    /* u-y */
    "--.." ,                                        /* z   */
  };
int main ( void )
{ 
  char text[100];
  fputs ( "enter some text to convert to morse: ", stdout );
  fflush ( stdout );
  if ( fgets ( text, sizeof text, stdin ) != NULL )
  {
    char *newline = strchr ( text, '\n' ); /* search for newline character */
    if ( newline != NULL )
    {
      *newline = '\0'; /* overwrite trailing newline */
    }
    printf ( "text = \"%s\"\n", text );
  }

  int j;
  int foo = strlen(text); 
  for ( j = 0; j < foo; j++ )
  {
    encode ( toupper ( text[j] ) );
  }
  getchar();
  getchar();
  return 0;
}

void encode ( char ch )
{
  size_t i, j;
  for ( i = 0; i < 26; ++i )
  {
    if ( ch == alph[i] )
    {
      printf ( "%s", morsecode[i] );
      break;
    }
  }
  putchar ( '\n' );
}

r5ing:

A few things:
» Don't use scanf or it's non-standard variants for accepting user input. There are better ways of achieving it. Read this.

» The way you expose the interface doesn't seem to be right. Make encode() return a char array instead of nothing.

» Also since Morse code is case insensitive you might consider converting the user input to uppercase before applying encode function to it.

> char *ch;
> printf("please enter char to convert to morse: ");
> scanf_s("%s", &ch);

How do you expect this to work? You are assigning the string entered by the user to something which doesn't belong to you. You need to allocate enough memory. Something like char ch[BUFSIZ] = { 0 }; Plus scanf requires you pass the starting address of the memory location. Since ch itself is a char array you just need to pass ch instead of &ch .

Member Avatar for iamthwee

well?

oooooooooooooooooooooooooooooooooooooooooooooooooooooooooo!
this works!!!
returns each char on a line. will chage this to return onto one line

S.O.S Thank you for the tips. i will read up on this. seems a bit advanced for me!! im a complete beginner!

Member Avatar for iamthwee

Mark this as being solved. (bottom rhs)

Next time use standard c and intent your code with spaces instead of tabs.

I also need to be able to read input from a file. I have wrtten read methods for java, where you can define how data is parsed. but i do not know how to write the file read method in C. How will i parse the data into the program as a string?

Member Avatar for iamthwee

What have you got so far?

void encode ( char ch );
char alph[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* morsecode is an array of pointers to char. It is initialized
* so that each element points to a string literal with
* the ascii representation of each char of the array alph[]
*/

char *morsecode[] =
  { /* an array of pointers to char */
    ".- "  , "-..." , "-.-." , "-.."  , "."    ,    /* a-e */
    "..-." , "--."  , "...." , ".."   , ".---" ,    /* f-j */
    "-.-"  , ".-.." , "--"   , "-."   , "---"  ,    /* k-o */
    ".--." , "--.-" , ".-."  , "..."  , "-"    ,    /* p-t */
    "..-"  , "...-" , ".--"  , "-..-" , "-.--" ,    /* u-y */
    "--.." ,                                        /* z   */
  };
int main ( void )
{ 
	for (;;) {
	printf("################################################\n");
	printf("##                                            ##\n");
	printf("##                  Main Menu                 ##\n");
	printf("##                                            ##\n");
	printf("################################################\n");
	printf("## Options: Type the option no: to proceed    ##\n");
	printf("## 1. Convert keyboard entry to morse code    ##\n");
	printf("## 2. Convert a file to morse code            ##\n");
	printf("## 3. Type Quit To Exit                       ##\n");
	printf("################################################\n\n");
	
	printf("## Enter an Option:                           ##\n");
	
	}


  char text[150];
  fputs ( "enter some text to convert to morse: ", stdout );
  fflush ( stdout );
  if ( fgets ( text, sizeof text, stdin ) != NULL )
  {
    char *newline = strchr ( text, '\n' ); /* search for newline character */
    if ( newline != NULL )
    {
      *newline = '\0'; /* overwrite trailing newline */
    }
    printf ( "text = \"%s\"\n", text );
  }
  putchar ( '\n' );

  int j;
  for ( j = 0; j < strlen ( text ); j++ )
  {
    encode ( toupper ( text[j] ) );
  }
  getchar();
  getchar();
  return 0;
}

void encode ( char ch )
{
  size_t i;
  for ( i = 0; i < 26; ++i )
  {
    if ( ch == alph[i] )
    {
      printf ( "%s ", morsecode[i] );
      break;
    }
  }
  
}

I need to get it to be something like this. so that i can meet the minimum requirements of the assessment.

i am thinking of useing a switch case statement, to call the encode function and i will write a separate function for the file read method.

iamthwee: i will mark it as solved if i do not need further assistance! Thanks for your help so far. I REALLY appreciate it!

i have to write that function yet. I didnt get that far bcuz i was stuck on the string bit. lol

Member Avatar for iamthwee

Oh right, well when you've written it, come back here.

sure mate. Coding it now

#include "stdafx.h"
#include "stdio.h"
#include "ctype.h"
#include "string.h"
#include "stdlib.h"



void encode ( char ch ); //encode function
void enter(); // text entry function
void file(); // read from a file function
void main_menu();

char alph[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/* morsecode is an array of pointers to char. It is initialized
* so that each element points to a string literal with
* the ascii representation of each char of the array alph[]
*/

char *morsecode[] =
  { /* an array of pointers to char */
    ".- "  , "-..." , "-.-." , "-.."  , "."    ,    /* a-e */
    "..-." , "--."  , "...." , ".."   , ".---" ,    /* f-j */
    "-.-"  , ".-.." , "--"   , "-."   , "---"  ,    /* k-o */
    ".--." , "--.-" , ".-."  , "..."  , "-"    ,    /* p-t */
    "..-"  , "...-" , ".--"  , "-..-" , "-.--" ,    /* u-y */
    "--.." ,                                        /* z   */
  };


int _tmain(int argc, _TCHAR* argv[]) {
	main_menu();
}
	

void main_menu() {
	int opt;
	printf("################################################\n");
	printf("##                                            ##\n");
	printf("##                  Main Menu                 ##\n");
	printf("##                                            ##\n");
	printf("################################################\n");
	printf("## Please Select An Option To Proceed         ##\n");
	printf("## 1. Convert keyboard entry to morse code    ##\n");
	printf("## 2. Convert a file to morse code            ##\n");
	printf("## 3. Exit                                    ##\n");
	printf("################################################\n\n");
	
	printf("Enter an Option: ");
	scanf_s("%d",&opt);
	
	if ((opt!= 1) && (opt != 2) && (opt != 3)) {	
	printf("\nInvalid Option..... Try Again: ");
	scanf_s("%d",&opt);
	}

	else if (opt == 1) {
	enter();
	}
	else if (opt == 2) { file();} 
	
	else if (opt == 3) { exit;} 
	}

void enter() {

  char text[150];
  fputs ( "Please Enter The Phrase You Would Like To Convert: ", stdout );
  gets(text);
  fflush ( stdout );
  if ( fgets ( text, sizeof text, stdin ) != NULL )
  {
    char *newline = strchr ( text, '\n' ); /* search for newline character */
    if ( newline != NULL )
    {
      *newline = '\0'; /* overwrite trailing newline */
    }
    printf ( "More Conversion Of = \"%s\"\n", text );
  }
  putchar ( '\n' );

  int j;
  for ( j = 0; j < strlen ( text ); j++ )
  {
    encode ( toupper ( text[j] ) );
  }
  getchar();
putchar ( '\n' );
main_menu();
}


void encode ( char ch ) {
  size_t i;
  for ( i = 0; i < 26; ++i )
  {
    if ( ch == alph[i] )
    {
      printf ( "%s ", morsecode[i] );
      break;
    }
  }
}
 
void file() {
  char path[150];
  fputs ( "Please Enter The Path Of The File You Would Like To Read From: ", stdout );
  gets(path);
  fflush ( stdout );
  if ( fgets ( path, sizeof path, stdin ) != NULL ) {

  char c;				/* Character read from the file.	*/
  FILE *ptr;			/* Pointer to the file. FILE is a
				   structure  defined in <stdio.h>	*/

				/* Open the file - no error checking done */
  ptr = fopen(path,"r");
				/* Read one character at a time, checking 
				   for the End of File. EOF is defined 
				   in <stdio.h>  as -1 			*/
  while ((c = fgetc(ptr)) != EOF)
  {
    encode(c);
  }

  fclose(ptr);			/* Close the file.			*/
}
}

heya. Been working on this.
Got the menu to work but the solution no longer works properly!
It only converts the frist letter of the string now....
Also the file read method causes the program to crash.. What am i doing wrong?

EDIT** Fixed the problem. Converts Fine now, however the read file method is not working.

Member Avatar for iamthwee

What does your input file look like. Post an example.

The input file will be a text file containing the data string to convert.
eg: when prompted user enters file path of c:\data.text
which contains the line "this is a english to morse conversion"
...
the program should convert that entire line using the encode function.
Hope that is helpful... BTW. Got the conversion working now :) thanks

Member Avatar for iamthwee

Keep it simple, do one thing at a time. Try to read in a file line by line. Then see if you can adapt that to include your morse program code.

#include <stdio.h> 
#include <stdlib.h> 

#define MYFILE "c:\\data.txt" 

int main(void)
{
  FILE *fp;
  char buf[BUFSIZ] = "crrrrrapppp";
  int i;
  
  if ((fp = fopen(MYFILE, "r")) == NULL)
  {
    perror (MYFILE);
    return (EXIT_FAILURE);
  }
  
  i = 0;

  while (fgets(buf, sizeof(buf), fp) != NULL)
  {
    printf ("Line %4d: %s", i, buf);
    i++;
  }
  
  fclose(fp);
    
  return(0);
}
Member Avatar for iamthwee

well?

yea.. im trying to get this to work.. get an error at the moment. will post in two mins

Says no such file currently. although the file exists!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.