gpt4 book ai didi

c - 将 char 从字符串传递到函数

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

我正在尝试将一些文本翻译为莫尔斯字母。当我发送一个字母来运行时,它可以正常工作,但我想让它写一个单词,所以我尝试用指针索引一个一个地发送单词,但它不会发生,请帮忙。

<小时/>

树结构:

typedef struct tree
{
char *letter;
char *morscode;
struct tree *left;
struct tree *right;
} tree;
<小时/>

功能:

tree *root=NULL;

void add (char* letter, char* morscode) {
if (root == NULL) {
root = (tree *)malloc(sizeof(tree));
root->letter = letter;
root->morscode = morscode;
root->left = NULL;
root->right = NULL;
}
else
{
tree *new = (tree *)malloc(sizeof(tree));
new->letter = letter;
new->morscode = morscode;
new->left = NULL;
new->right = NULL;

tree *node = root,
*mom;
while (node != NULL) {
mom = node;
if (strcmp(letter, dugum->letter) == -1)
node = node->left;
else
node = node->right;
}
if (strcmp(letter, mom->letter) == -1)
mom->right = new;
else
mom->right = new;
}
}

tree *searchbyletter(char& letter, agac *node) {

if(strcmp(letter,node->letter) == -1)
searchbyletter(letter, node->left);
else if(strcmp(letter, node->letter) == 1)
searchbyletter(letter, node->right);
else
return node;
}

void write(char *letter) {
int x = strlen(letter),
i;
for(i = 0; i < x; i++) {
printf("%s", searchbyletter(letter[i], root)->morscode);
}
}

void preorder(tree *node) {
if (node != NULL) {
printf(" %s ", node->letter);
preorder(node->left);
preorder(node->right);
}
}

void inorder(tree *node) {
if (node != NULL) {
inorder(node->left);
printf(" %s ", node->letter);
inorder(node->right);
}
}

void postorder(tree *node) {
if (node!=NULL) {
postorder(node->left);
postorder(node->right);
printf(" %s ", node->letter);
}
}
<小时/>

主要: [我手动初始化了摩尔斯电码和字母。]

void main() {
char* arr[27][2] = {
{" ", " "}, {"E", "."},
{"T", "-"}, {"I", ".."},
{"A", ".-"}, {"N", "-."},
{"M", "--"}, {"S", "..."},
{"U", "..-"}, {"R", ".-."},
{"W", ".--"}, {"D", "-.."},
{"K", "-.-"}, {"G", "--."},
{"O", "---"}, {"H", "...."},
{"V", "...-"}, {"F", "..-."},
{"L", ".-.."}, {"P", ".--."},
{"J", ".---"}, {"B", "-..."},
{"X", "-..-"}, {"C", "-.-."},
{"Y", "-.--"}, {"Z", "--.."},
{"Q", "--.-"}
};
int i, j;
for(i = 0; i < 27; i++) {
add(arr[i][0], arr[i][1]);
}
preorder(kok);
printf("\n");
inorder(kok);
printf("\n");
postorder(kok);
printf("\n");
write("HELLO WORLD");
}

最佳答案

我的猜测是问题出在使用 strcmp 函数比较单个字符(例如,strcmp(letter,node->letter))。

此函数 (strcmp) 比较以 null 结尾的 C 字符串,因此在您的情况下,当您尝试比较字母“B”时,它实际上会比较字符串“BA”。

您可以使用 == 运算符比较字符,如下所示:
if(字母==节点->字母)

但是,当然,如果没有完整的代码片段,就很难说。

关于c - 将 char 从字符串传递到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53861209/

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