diff --git a/cv7/program.c b/cv7/program.c index 0a39228..6d7b9d8 100644 --- a/cv7/program.c +++ b/cv7/program.c @@ -11,6 +11,10 @@ typedef struct Node { // Function to create a new node Node* createNode(char* text) { Node* node = (Node*)malloc(sizeof(Node)); + if (!node) { + fprintf(stderr, "Chyba pri alokacii pamate.\n"); + exit(1); + } strcpy(node->text, text); node->yes = NULL; node->no = NULL; @@ -18,10 +22,10 @@ Node* createNode(char* text) { } // Recursive function to read and build the tree -Node* readTree(FILE* file, int* count) { +Node* readTree(int* count) { char line[100]; - if (!fgets(line, sizeof(line), file) || strcmp(line, "\n") == 0) { + if (!fgets(line, sizeof(line), stdin) || strcmp(line, "\n") == 0) { return NULL; } @@ -36,8 +40,8 @@ Node* readTree(FILE* file, int* count) { // If it's a question, create a node and recursively read its children Node* node = createNode(line); - node->yes = readTree(file, count); - node->no = readTree(file, count); + node->yes = readTree(count); + node->no = readTree(count); return node; } @@ -47,6 +51,7 @@ void queryUser(Node* node) { if (node->yes == NULL && node->no == NULL) { printf("Expert z bufetu to vie. Je to: %s\n", node->text); + printf("Koniec\n"); return; } @@ -55,7 +60,10 @@ void queryUser(Node* node) { printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n"); char answer; - scanf(" %c", &answer); + if (scanf(" %c", &answer) != 1) { + printf("Nespravny vstup.\n"); + return; + } if (answer == 'a') { queryUser(node->yes); @@ -75,15 +83,8 @@ void freeTree(Node* node) { } int main() { - FILE* file = fopen("baza.txt", "r"); - if (!file) { - printf("Chyba pri nacitani suboru.\n"); - return 1; - } - int count = 0; - Node* root = readTree(file, &count); - fclose(file); + Node* root = readTree(&count); if (root == NULL) { printf("Chyba pri nacitani baze pravidiel.\n");