usaa24/cv7/program.c

99 lines
2.2 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char text[100];
struct Node* yes;
struct Node* no;
} Node;
// Function to create a new node
Node* createNode(char* text) {
Node* node = (Node*)malloc(sizeof(Node));
strcpy(node->text, text);
node->yes = NULL;
node->no = NULL;
return node;
}
// Recursive function to read and build the tree
Node* readTree(FILE* file, int* count) {
char line[100];
if (!fgets(line, sizeof(line), file) || strcmp(line, "\n") == 0) {
return NULL;
}
// Remove newline character from line
line[strcspn(line, "\n")] = 0;
// Check if the line is an answer (starts with '*')
if (line[0] == '*') {
(*count)++;
return createNode(line + 1); // Skip the '*' character
}
// 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);
return node;
}
// Function to interact with the user and navigate the tree
void queryUser(Node* node) {
if (node == NULL) return;
if (node->yes == NULL && node->no == NULL) {
printf("Expert z bufetu to vie. Je to: %s\n", node->text);
return;
}
// Print question and get user's answer
printf("%s\n", node->text);
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
char answer;
scanf(" %c", &answer);
if (answer == 'a') {
queryUser(node->yes);
} else if (answer == 'n') {
queryUser(node->no);
} else {
printf("Nespravny vstup.\n");
}
}
// Function to free the tree
void freeTree(Node* node) {
if (node == NULL) return;
freeTree(node->yes);
freeTree(node->no);
free(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);
if (root == NULL) {
printf("Chyba pri nacitani baze pravidiel.\n");
return 1;
}
printf("Pozna %d druhov ovocia a zeleniny.\n", count);
queryUser(root);
freeTree(root);
return 0;
}