此代码基本上是获取用户输入的 (a-z) 并将其转换为摩尔斯电码。但是返回字符串的末尾总是有 'm' 试图做数百万的事情来修复它你能看到我做错了什么吗,谢谢。
//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;
}
最佳答案
你的循环绕过一个额外的字符。外循环查找 *pp 为\0,但 *pp 仍然是前一个字符的值。
将其更改为:
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
我发现它的方法是在调试器下运行并观察发生了什么。尽管我只输入了一个字符,但当它绕过两次循环时,它很快就变得很明显了。使用调试器,这是一个很棒的工具。通过调试器单步执行代码是值得的,即使您认为它在工作。有时你会得到惊喜!
关于代码在创建的字符串末尾不断给我 m,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505127/