我一直在嘗試通過檔案處理將一個節點插入到我的樹中,但它總是只插入一個節點,然后程式將強制關閉自己。我試圖將資料放在鏈表上并且它有效。所以這里的問題可能不是 file.txt 本身,而是我的樹。有人可以告訴我我在哪里做錯了嗎?
這是我的樹演算法
struct user {
char username[50];
int money;
char favorite[50];
user *left;
user *right;
};
user *root = NULL;
user *userTree(char username[], int money, char favorite[]) {
user *newBranch = (user *) malloc(sizeof(user));
strcpy(newBranch->favorite, favorite);
strcpy(newBranch->username, username);
newBranch->money = money;
return newBranch;
}
user *insertUser(user *root,char username[], int money, char favorite[]) {
if (root == NULL) {
return userTree(username ,money, favorite);
}
else if (strcmp(username, root->username) < 0) {
root->left = insertUser(root->left, username, money, favorite);
}
else {
root->right = insertUser(root->right, username, money, favorite);
}
return root;
}
這是我的檔案處理演算法
void insertCredential() {
FILE* fr = fopen("users/users.txt", "r");
while (!feof(fr)) {
char username[50], garbage[50], favorite[50];
int money;
fscanf(fr, "%[^#]#%[^#]#%d#%[^\n]\n", username, garbage, &money, favorite);
root = insertUser(root, username, money, favorite);
puts("test insert");
}
fclose(fr);
}
我試圖將資料放在一個鏈表中并且它有效,但我想知道為什么我不能將它插入到樹上
uj5u.com熱心網友回復:
至少有這些問題:
代碼不會在 malloc() 之后初始化左右成員,從而導致未定義的行為。. 考慮
calloc()。@trincotwhile (!feof(fr))錯了。@安德烈亞斯文澤爾。檢查回傳值fscanf()。"%[^#]#%[^#]#%d#%[^\n]\n"缺少允許輸入溢位的寬度。添加寬度。"I[^#]#I[^#]#%d#I[^\n]\n"fopen()未檢查的結果。分配重新調整的指標未檢查成功。
代碼不是有效的 C。看起來像使用了 C 編譯器:
user *root = NULL;-->struct user *root = NULL;。@一些程式員老兄
缺點:
money因為int可能太窄了。考慮long一個寬度:"%d"-->"%9ld"。在 C中不需要強制
newBranch = (user *) malloc(sizeof(user));轉換。當大小參考物件而不是型別時更容易維護:newBranch = malloc(sizeof newBranch[0]);更適用
const于未更改的參考資料:userTree(char username[], int money, char favorite[])-->userTree(const char username[], int money, const char favorite[])。尾隨
"\n"可以讀取多個空格。更好的錯誤檢查,用于fgets()讀取 1行面向行的資料,然后決議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/532220.html
標籤:C数据结构文件处理
