我有一个内部有字母的结构,我想将这些字母赋给一个数组,这样我以后就可以使用它了。如果我只打印字母就可以了。
顶部(结构):
#include "stdafx.h"
typedef struct { char* code; char* letter;}morse_tabelle;
morse_tabelle tabelle[] = {
{ ".-", "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" },
{ "/", " " },
};
对于数组大小:
#define ARR_SIZE(x) (sizeof(x)/sizeof((x)[0]))
功能:
void morse_to_text(void)
{
char input[100];
char* morse_letter;
int j = 0;
char* translation[50];
printf_s("\n\nput in Morsecode:\n\n");
fgets(input, 100, stdin);
input[strlen(input)-1] = '\0';
morse_letter = strtok(input, " ");
while (morse_letter)
{
for (int i = 0; i < ARR_SIZE(tabelle); i++)
{
if (!strcmp(morse_letter, tabelle[i].code))
{
translation[j] = tabelle[i].letter;
j++;
/*printf_s("%s", tabelle[i].letter);*/ //This works
}
}
morse_letter = strtok(NULL, " ");
}
/*output*/
printf_s("\n\n---------------\n\n");
for (int i = 0; i <= strlen(translation[50]); i++){
printf("%s", translation[i]);
}
};
如果我将结构内的 char* letter
更改为 char letter
,它就可以工作了。但后来我得到一个缓冲区溢出。
问题又来了:如何将字符串存储在数组中。
最佳答案
你真正想要的是:
char translation[50]; // no string array, char array!
然后按照您的意愿将字母设置为字符:
typedef struct { char* code; char letter;} morse_tabelle;
有了它,你现在可以简单地做
translation[j] = tabelle[i].letter;
再一次,就像以前一样。只是数据类型改变了...
但是,您需要以 null 终止翻译后的字符串,否则您不能将其用于 printf("%s", translation)
while(...) { ... }
translation[j] = 0;
// output:
// no for loop any more!
printf("%s", translation);
终止空字符的替代方法是将长度提供给 printf 格式参数:
while(...) { ... }
// no termination any more...
// output:
// no for loop any more!
printf("%.*s", j, translation);
参见 printf有关详细信息(好吧,链接实际上是 C++,但文档也完全适用于 C...)。
关于c - 将文本从结构中保存在 char 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43755045/