[英]Translator with BST in C
因此,我正在编写一个程序,该程序可以从键盘上输入一个单词,然后使用包含所有翻译内容的文件输出其西班牙语翻译。 现在,我正在使用BST作为功能。 在我的代码中,我使用strtok()分解了从文件输入的字符串。 但是,每个单词前面都有四个随机字符。 这就是我所拥有的...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 8001
// BST code
struct BSTnode{
char engWord[128], spanWord[1000];
struct BSTnode *left, *right;
};
struct BSTnode *root = NULL;
struct BSTnode *newBSTNode(char *engWord, char *spanWord){
struct BSTnode *newNode;
newNode = (struct BSTnode*)malloc(sizeof(struct BSTnode));
strcpy(newNode->engWord, engWord);
strcpy(newNode->spanWord, spanWord);
newNode->left = newNode->right = NULL;
return newNode;
}
void insert(char *engWord, char *spanWord){
struct BSTnode *parent, *current, *newnode = NULL;
int res = 0;
if(root == NULL){
root = newBSTNode(engWord, spanWord);
return;
}
for(current = root; current != NULL;
current = (res > 0)?current- >right:current->left){
res = strcasecmp(engWord, current->engWord);
parent = current;
}
newnode = newBSTNode(engWord, spanWord);
res > 0?(parent->right = newnode):(parent->left = newnode);
return;
}
void findEngWord(char *str){
struct BSTnode *temp = NULL;
int flag = 0, res = 0;
if(root == NULL){
printf("FAIL!!!!!!");
return;
}
temp = root;
int counter = 1;
while(temp){
if((res = strcasecmp(temp->engWord, str)) == 0){
printf("\t%s\n\t%d BST nodes", temp->spanWord, counter);
flag = 1;
break;
}
temp = (res > 0)?temp->left:temp->right;
counter++;
}
if(!flag)
printf("\t---NOT found (in BST)\n\t%d BST nodes", counter);
return;
}
void openFileBST(){
// open file
FILE* filePnt = fopen("Spanish.txt", "r");
char input[500], *first, *second;
// If file is invalid
if(filePnt == NULL){
printf("Could not open file. Termination Program...");
exit(0);
}
while(fgets(input, 500, filePnt) != NULL){
first = strtok(filePnt, "\t");
second = strtok(NULL, "\n");
// Test prints
printf("%s\n", &first);
printf("%s\n", &second);
insert(&first, &second);
}
fclose(filePnt);
}
void search(){
char *tempStr, exitStr = "-1";
// Ask user to input word
printf("Enter a word you want to have translated. (type -1 to exit)
\n-------------------------\n");
while(1){
printf("\n- ");
fgets(tempStr, 99, stdin);
// Failed exit statement
//if(strcmp(tempStr, exitStr) == 0){
// printf("test");
// break;
//}
findEngWord(&tempStr);
}
}
int main()
{
openFileBST();
search();
}
由于前四个字符,我敢肯定我无法正确搜索英文单词。 我的strtok函数或代码有问题吗? 谢谢大家的帮助!
在openFileBST
函数中,变量first
和second
的类型为char *
。 现在,如果您获得了指向这些变量的指针,例如&first
,您将得到char **
类型的东西。 与您期望的其他功能(或带有"%s"
格式的printf
)不同。
将变量传递给函数时,请删除地址运算符&
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.