Update a1/program.c

This commit is contained in:
Viktor Daniv 2024-10-26 19:31:08 +00:00
parent fbe547c8bc
commit 14fe6bb5c0

View File

@ -1,60 +1,68 @@
#include <stdio.h> #include <stdio.h>
#include <string.h>
#define MAX 100 #define MAX 100
void serch_zatv(char vhod[MAX]) { // Pomocná funkcia na kontrolu páru zátvoriek
char first[2] = "{}"; int is_matching_pair(char open, char close) {
char second[2] = "[]"; return (open == '(' && close == ')') ||
char third[2] = "<>"; (open == '{' && close == '}') ||
char fourth[2] = "()"; (open == '[' && close == ']') ||
int idx = 0; (open == '<' && close == '>');
int idt = 0; }
char find[50] = {0};
while (vhod[idx] != '\0') { // Funkcia na kontrolu správnosti zátvoriek
if (vhod[idx] == first[0]) { void check_brackets(const char *code) {
find[idt] = first[1]; char stack[MAX];
idt++; int stack_top = -1; // vrchol zásobníka
} else if (vhod[idx] == second[0]) {
find[idt] = second[1]; printf("Read: %s\n", code);
idt++;
} else if (vhod[idx] == third[0]) { for (int i = 0; code[i] != '\0'; i++) {
find[idt] = third[1]; char c = code[i];
idt++;
} else if (vhod[idx] == fourth[0]) { // Ak je znak otváracia zátvorka, pridaj ho na zásobník
find[idt] = fourth[1]; if (c == '(' || c == '{' || c == '[' || c == '<') {
idt++; if (stack_top >= MAX - 1) {
printf("Stack overflow at position %d\n", i);
return;
}
stack[++stack_top] = c;
}
// Ak je znak zatváracia zátvorka
else if (c == ')' || c == '}' || c == ']' || c == '>') {
if (stack_top < 0) {
printf("Unexpected closing bracket %c at position %d\n", c, i);
return;
}
char top = stack[stack_top--];
if (!is_matching_pair(top, c)) {
printf("Crossed bracket %c in %d, expected %c\n", c, i, top);
return;
}
}
}
// Skontroluj, či sú všetky zátvorky uzavreté
if (stack_top >= 0) {
printf("Unmatched bracket at the end\n");
} else { } else {
for (int i = 0; i < idt; i++) { printf("All brackets OK\n");
if (vhod[idx] == find[i]) {
find[i] = '.';
for (int r = i + 1; r < idt; r++) {
if (find[r] != '.' && find[r] != '\0') {
printf("Crossed bracket %c at position %d, expected %c\n", vhod[idx], idx, find[i]);
return;
} }
} }
break;
}
}
}
idx++;
}
for (int i = 0; i < idt; i++) {
if (find[i] != '.' && find[i] != '\0') {
printf("Unmatched bracket\n");
return;
}
}
printf("Read: %s\nAll brackets OK\n", vhod);
}
int main() { int main() {
char riadok[MAX]; char code[MAX];
scanf("%s", riadok); // Без амперсанда &
serch_zatv(riadok); // Načítaj vstup
printf("Enter code: ");
fgets(code, MAX, stdin);
// Odstráň novoriadok na konci
code[strcspn(code, "\n")] = '\0';
// Skontroluj zátvorky
check_brackets(code);
return 0; return 0;
} }