gpt4 book ai didi

c - 打印正确的莫尔斯电码以进行字母输入

转载 作者:行者123 更新时间:2023-11-30 19:51:38 24 4
gpt4 key购买 nike

我现在需要输出相当于字母数字输入的摩尔斯电码。我的检查条件是 if 循环:我尝试使用 alpha 数组的每个元素查看输入数组的每个元素,但似乎从未找到匹配项。我不确定我是否使用了正确的方法。我尝试取消引用要输入的点,并将该值与 alpha 的每个元素进行比较,直到找到匹配项。如果未找到匹配项,则会发生错误。

不工作:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>

int main(void)
{

char *morse[] = {"/",
".-","-...","-.-.","-..",".","..-.","--","....","..",".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
"..-","...-",".--","-..-","-.--","--..",
"-----",".----","..---","...--","....-",".....","-....","--...","---..","----."};
char *alpha[]= {" ",
"A","B","C","D","E","F","G","H","I","J",
"K","L","M","N","O","P","Q","R","S","T",
"U","V","W","X","Y", "Z",
"0", "1","2","3","4","5","6","7","8","9"};


char *print_array[50];
int print_array_index = 0;

char hold[50];
int hold_index = 0;

char input[200];
int i = 0;

printf("welcome to the Morse translator.\n");
printf("Enter input: ");
fgets(input, sizeof(input), stdin);

char *p;
for (p=input; *p !='\0';++p)
{
*p = toupper(*p);
}

if (input[0]=='-' || input[0]=='.')
{


while (input[i] !='\0') {

if (input[i] ==' ' || input[i] == '\n')
{
hold[hold_index] = '\0';

bool found = false;

for (int x = 0; x < sizeof(morse) / sizeof(char *); x++)
{
if (strcmp(morse[x], hold) == 0)
{
print_array[print_array_index++] = alpha[x];

found = true;

break;
}
}

if (!found)
{
fprintf(stderr, "invalid Morse code!\n");
}

hold_index = 0;
}
else
{
hold[hold_index++] = input[i];
}

i++;
}

for (int x = 0; x < print_array_index; x++)
{
printf("%s", print_array[x]);

}

printf("\n");
}
else if (isalnum(input[0]))
{
while (input[i]!='\0')
{
if (input[i] ==' ' || input[i] == '\n')
{
bool found = false;
for (int x=0; x < sizeof(alpha)/sizeof (char*);x++)
{
if (alpha[x]==input[i])
{
print_array [print_array_index++] = alpha[x];
found = true;
break;
}
}
if (!found)
{
fprintf(stderr, "Invalid input!\n");
}
hold_index = 0;
}
i++;
}
for (int x=0; x < print_array_index; x++)
{
printf("%s",print_array[x]);
}
printf("\n");
}
return 0;
}

最佳答案

else if (isalnum(input[0])){ 的一部分应该类似于

else if (isalnum(input[0])){
while (input[i]!='\0' && input[i]!='\n'){
bool found = false;
for (int x=0; x < sizeof(alpha)/sizeof(char*);x++){
if (*alpha[x]==input[i]){
print_array[print_array_index++] = morse[x];
found = true;
break;
}
}
if(!found){
fprintf(stderr, "Invalid input!\n");
}
i++;
}
for (int x=0; x < print_array_index; x++){
printf("%s", print_array[x]);
}
printf("\n");
}

关于c - 打印正确的莫尔斯电码以进行字母输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39685792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com