Update cv7/program.c

This commit is contained in:
Marat Izmailov 2024-11-13 21:17:06 +00:00
parent cd502360a7
commit 6e022baaca

View File

@ -27,7 +27,7 @@ void free_tree(Node *root) {
int count_answers(Node *root) {
if (!root) return 0;
if (root->yes == NULL && root->no == NULL) return 1; // It's an answer
if (root->yes == NULL && root->no == NULL) return 1;
return count_answers(root->yes) + count_answers(root->no);
}
@ -38,11 +38,11 @@ Node* parse_rules() {
int stack_top = -1;
while (fgets(line, sizeof(line), stdin)) {
// Trim newline and spaces
// Trim newline
line[strcspn(line, "\n")] = 0;
if (strlen(line) == 0) break; // End of rules
if (strlen(line) == 0) break;
if (line[0] == '*') { // This is an answer
if (line[0] == '*') {
Node *answer = create_node(line + 1);
if (stack_top >= 0) {
if (stack[stack_top]->yes == NULL)
@ -50,7 +50,7 @@ Node* parse_rules() {
else
stack[stack_top]->no = answer;
}
} else { // This is a question
} else {
Node *question = create_node(line);
if (stack_top >= 0) {
if (stack[stack_top]->yes == NULL)
@ -76,27 +76,19 @@ void ask_question(Node *node) {
return;
}
// Print the current question
printf("%s?\n", node->content);
if (node->yes) {
printf("* %s\n", node->yes->content);
printf("%s\n", node->content);
if (node->yes && node->yes->content[0] != '*') {
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
}
if (node->no) {
printf("* %s\n", node->no->content);
}
// Prompt for input
printf("\n");
printf("n\n");
char response;
while (1) {
response = getchar();
getchar(); // To capture newline
if (response == 'n') {
if (response == 'a' && node->yes) {
ask_question(node->yes);
break;
} else if (response == 'n') {
} else if (response == 'n' && node->no) {
ask_question(node->no);
break;
} else {
@ -107,7 +99,6 @@ void ask_question(Node *node) {
}
int main() {
// General system information only once
printf("Expert z bufetu to vie.\n");
Node *root = parse_rules();
@ -119,9 +110,11 @@ int main() {
int answer_count = count_answers(root);
printf("Pozna %d druhov ovocia a zeleniny.\n", answer_count);
// Ask the first question
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
ask_question(root);
if (root) {
printf("Odpovedajte 'a' pre prvu moznost alebo 'n' pre druhu moznost.\n");
ask_question(root);
}
free_tree(root);
return 0;