Update cv7/program.c

This commit is contained in:
Marat Izmailov 2024-11-13 22:48:03 +00:00
parent 1c188d677a
commit 201846cfd9

View File

@ -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");