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