二分木のプログラムを作っています.
文字列の読み込みができないのはなぜでしょうか.
ファイルオープンのエラーはありません.
c
1#include <stdio.h> 2#include<stdlib.h> 3#include<string.h> 4 5typedef struct BTREE_ { 6 struct BTREE_ *left, *right; 7 char data[20]; 8}Btree; 9 10Btree *newCell(char *data) { 11 Btree *bp; 12 bp = (Btree *)malloc(sizeof(Btree)); 13 bp->left = NULL; 14 bp->right = NULL; 15 strcpy(bp->data, data); 16 return bp; 17} 18Btree *registBtree(Btree *node, char *newdata) { 19 int len1, len2; 20 len1 = strlen(node->data); 21 len2 = strlen(newdata); 22 if (node == NULL) { 23 node = newCell(newdata); 24 } 25 else if (len2 < len1) { 26 node->left = registBtree(node->left, newdata); 27 } 28 else { 29 node->right = registBtree(node->right, newdata); 30 } 31 return node; 32} 33/* 部分木の全ての値を出力 */ 34Btree *printBtree(Btree *node) { 35 if (node == NULL) { 36 return NULL; 37 } 38 printBtree(node->left); 39 printf("data[%s]\n", node->data); 40 printBtree(node->right); 41 return node; 42} 43int main() { 44 FILE*fp; 45 Btree *start; 46 //int newdata = 0; 47 char newdata[20]; 48 if ((fp = fopen("food.txt", "r")) == NULL) { 49 fprintf(stderr, "%s\n", "error: can't read file."); 50 return EXIT_FAILURE; 51 } 52 fscanf(fp, "%s", newdata);//root 53 start = newCell(newdata); 54 while (fscanf(fp, "%s", newdata) != EOF) { 55 registBtree(start, newdata); 56 } 57 printBtree(start); 58 return 0; 59} 60
food.txt はどのような内容でしょうか.
各部に変数の表示等を入れて, 実際にどのようにプログラムが動いたのかを確認されましたか? されてましたらその時のコードと結果を追記して頂けますでしょうか.
されていなければ, まずその確認をして頂いて, コードと共に結果を追記して頂けますでしょうか.
回答2件
あなたの回答
tips
プレビュー