gpt4 book ai didi

c - 字符串到数组,然后在 c 中打印

转载 作者:行者123 更新时间:2023-11-30 15:05:43 25 4
gpt4 key购买 nike

我试图获取用户输入的字符串并查看每个代码以查看它是否出现在另一个字符串中。到目前为止我的代码有效。如果成功找到该单词,则 alpha 表示将被添加到最终将打印的数组中,但前提是找到所有代码。

我对存储在要打印的数组中的内容有疑问。

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

typedef char *string;
typedef char *alpha;

int main(void)
{
string morse[4]={".-", "-...","----.", ".."};
string alpha[4]={"A", "B", "9", "I"};
char prntArr[50];
char *input;
char *hold;
input = malloc(200);
hold = malloc(50);
int i=0;
int j=0;
int ret;
int x;
int w=0;
int z=0;
printf("please enter a string\n");
scanf("%[^\n]",input);

do{
if (input[i] !=' ')
{
hold[j] = input[i];
j++;
}
else
{
hold[j]='\0';

for (x=0;x<4;x++)
{
printf("value of x %d\n",x);

ret = strcmp(morse[x], hold);
if (ret==0)
{
printf("%s\n",alpha[x]);

prntArr[w]=*hold;
w++;
x=4;
}
else
{
ret=1;
printf("invalid Morse code!");

}
}
j = 0;
}
i++;
}while(input[i] !='\0');

for (z=0;z<50;z++)
{
printf("%c",prntArr[z]);
}

return 0;
free(input);
}

最佳答案

您所询问的问题是由程序中使用prntArr的方式引起的。它实际上应该是一个指向 alpha 数组的字符指针数组。相反,它被作为一个字符数组来操作,每个莫尔斯电码元素的第一个字符都存储在其中。当它被打印时,跟踪数组使用量的变量将被简单地忽略。

另一个问题是您的代码使用空格来破坏代码,但行尾不一定有空格,因此可能会丢失代码。在下面的程序中,我将 scanf() 替换为 fgets(),这会在输入末尾留下一个换行符,我们可以使用它(例如空格)来指示代码结束。

其他问题:您在代码中的错误位置打印了invalid Morse code消息,并将其打印到stdout而不是stderr ;您记得释放input,但忘记释放hold;您将代码放在永远不会被调用的 return 之后。

下面是对代码的修改,解决了上述问题以及一些样式问题:

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

int main(void)
{
char *morse[] = {".-", "-...", "----.", ".."};
char *alpha[] = {"A" , "B" , "9" , "I" };

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

char hold[50];
int hold_index = 0;

char input[200];
int i = 0;

printf("please enter a string: ");
fgets(input, sizeof(input), stdin);

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: %s\n", hold);
}

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");

return 0;
}

示例运行

> ./a.out
please enter a string: ----. -... .- ..
9 B A I
>

> ./a.out
please enter a string: .- --- ..
invalid Morse code: ---
A I
>

关于c - 字符串到数组,然后在 c 中打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39682940/

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