This code basically takes what a user puts (a-z) in and converts it into morse code. But the return string always has 'm' at the end tried to do a millions of stuff to fix it can you see what I have done wrong, thanks.
//Functions
#include "stdafx.h"
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void morse(void); //prototype
int _tmain(int argc, _TCHAR* argv[])
{
for(;;){
morse(); // function call
}
}
void morse(void){
char *ss= (char*)malloc(110); // allocating dynamic memory
strcpy(ss, ".- -...-.-.-.. . ..-.--. ...... .----.- .-..-- -. --- .--.--.-.-. ... - ..- ...-.-- -..--.----..");
char *pp =(char*)malloc(110);
int i = 0;
int n = 0;
printf("Enter text to convert to morse code: ");
scanf("%s", pp);
char *q =(char*)malloc(110);
while (*pp != '\0'){//intiate while loop
*pp = *(pp + n);
int f = (*pp - 97)*4; //find letters postion in morse code string
int a = 0;
while (a != 4) //copy morse code for the letter into new string
{
*(q + i) = *(ss + f);
i++;
a++;
f++;
}
n++;
}
q[i] = '\0';
printf("%s", q); //return morse code
printf("\n");
free(ss); //free the allocated memory
free(pp);
free(q);
return;
}
Your loop goes around for one extra character. The outer loop looks for *pp being \0, but *pp is still the prior character's value.
Change it to:
while (*(pp+n) != '\0') { // test next character
char c = *(pp + n); // fetch next character
int f = (c - 97)*4; // find character's index into morse array
The way I found this was to run under the debugger and watch what was going on. It soon became apparent when it went around the loop twice even though I'd entered only one character. Use the debugger, it's a great tool. It's worth stepping through code through the debugger, even if you think it's working. Sometimes you get a surprise!