usaa25/a1/program.c
2025-10-21 19:06:36 +02:00

74 lines
1.7 KiB
C

#include <stdio.h>
#include <string.h>
#define MAX 101
char expected_close(char open) {
switch (open) {
case '(': return ')';
case '{': return '}';
case '[': return ']';
case '<': return '>';
default: return 0;
}
}
int main(void) {
char line[MAX];
char stack[MAX];
int pos[MAX];
int top = -1;
if (fgets(line, MAX, stdin) == NULL)
return 0;
line[strcspn(line, "\n")] = '\0';
printf("Read: %s\n", line);
int ok = 1;
int length = strlen(line);
for (int i = 0; i < length; i++) {
char ch = line[i];
if (ch == '(' || ch == '{' || ch == '[' || ch == '<') {
top++;
stack[top] = ch;
pos[top] = i; // 0-indexovaná pozícia, may be used elsewhere
}
else if (ch == ')' || ch == '}' || ch == ']' || ch == '>') {
if (top < 0) {
printf("Unexpected closing bracket %c in %d\n", ch, i);
ok = 0;
break;
}
char last_open = stack[top];
char expected = expected_close(last_open);
if (ch != expected) {
printf("Crossed bracket %c in %d, expected %c \n", ch, i, expected);
ok = 0;
break;
}
top--;
}
}
if (ok && top >= 0) {
// Vytvoríme reťazec všetkých chýbajúcich zatváracích zátvoriek v poradí, ktoré treba doplniť.
printf("Missing closing brackets: ");
for (int i = top; i >= 0; i--) {
char c = expected_close(stack[i]);
if (c) putchar(c);
}
putchar('\n');
ok = 0;
}
if (ok)
printf("All brackets OK\n");
return 0;
}