usaa24/a1/program.c

78 lines
2.1 KiB
C
Raw Permalink Normal View History

2024-10-31 23:33:04 +00:00
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
typedef struct {
char bracket;
int position;
} StackItem;
int main() {
char line[MAX_LEN + 1];
StackItem stack[MAX_LEN];
2024-10-31 23:35:07 +00:00
int top = -1;
2024-10-31 23:33:04 +00:00
2024-10-31 23:37:39 +00:00
2024-10-31 23:33:04 +00:00
fgets(line, sizeof(line), stdin);
2024-10-31 23:37:39 +00:00
// Odstránenie nového riadku na konci vstupu, ak existuje
2024-10-31 23:35:07 +00:00
line[strcspn(line, "\n")] = 0;
printf("Read: %s\n", line);
2024-10-31 23:33:04 +00:00
for (int i = 0; line[i] != '\0'; i++) {
char ch = line[i];
if (ch == '(' || ch == '{' || ch == '[' || ch == '<') {
if (top < MAX_LEN - 1) {
stack[++top].bracket = ch;
stack[top].position = i;
}
2024-10-31 23:35:07 +00:00
} else if (ch == ')' || ch == '}' || ch == ']' || ch == '>') {
2024-10-31 23:33:04 +00:00
if (top == -1) {
2024-10-31 23:35:07 +00:00
printf("Unexpected closing bracket %c in %d\n", ch, i);
2024-10-31 23:33:04 +00:00
return 0;
}
char opening = stack[top].bracket;
int opening_pos = stack[top].position;
top--;
if ((opening == '(' && ch != ')') ||
(opening == '{' && ch != '}') ||
(opening == '[' && ch != ']') ||
(opening == '<' && ch != '>')) {
char expected;
switch (opening) {
case '(': expected = ')'; break;
case '{': expected = '}'; break;
case '[': expected = ']'; break;
case '<': expected = '>'; break;
}
2024-10-31 23:43:37 +00:00
printf("Crossed bracket %c in %d, expected %c \n", ch, i, expected);
2024-10-31 23:42:46 +00:00
2024-10-31 23:33:04 +00:00
return 0;
}
}
}
if (top != -1) {
2024-10-31 23:37:39 +00:00
printf("Missing closing brackets: ");
while (top != -1) {
char expected;
switch (stack[top--].bracket) {
case '(': expected = ')'; break;
case '{': expected = '}'; break;
case '[': expected = ']'; break;
case '<': expected = '>'; break;
}
printf("%c", expected);
}
printf("\n");
2024-10-31 23:33:04 +00:00
} else {
printf("All brackets OK\n");
}
return 0;
}