usaa24/a1/program.c

44 lines
1.1 KiB
C
Raw Normal View History

2024-10-31 18:45:11 +00:00
#include <stdio.h>
2024-10-31 18:46:23 +00:00
#include <string.h>
2024-10-31 18:45:11 +00:00
int match(char open, char close) {
2024-10-31 19:02:33 +00:00
return (open == '{' && close == '}') || (open == '[' && close == ']') ||
(open == '(' && close == ')');
2024-10-31 18:45:11 +00:00
}
void check_brackets(const char *code) {
char stack[100];
2024-10-31 18:46:23 +00:00
int top = -1;
2024-10-31 18:45:11 +00:00
2024-10-31 22:26:55 +00:00
printf("Read: %s", code);
2024-10-31 18:45:11 +00:00
2024-10-31 18:46:23 +00:00
for (int i = 0; code[i] != '\0'; i++) {
2024-10-31 18:45:11 +00:00
char c = code[i];
2024-10-31 19:02:33 +00:00
if (c == '{' || c == '[' || c == '(') {
stack[++top] = c;
} else if (c == '}' || c == ']' || c == ')') {
if (top == -1) {
2024-10-31 22:28:57 +00:00
printf("Unexpected closing bracket %c in %d\n", c, i);
2024-10-31 19:02:33 +00:00
return;
2024-10-31 18:46:23 +00:00
}
2024-10-31 19:02:33 +00:00
if (!match(stack[top], c)) {
printf("Crossed bracket %c in %d, expected %c\n", c, i, stack[top]);
2024-10-31 18:45:11 +00:00
return;
}
2024-10-31 18:46:23 +00:00
top--;
2024-10-31 18:45:11 +00:00
}
}
2024-10-31 18:46:23 +00:00
if (top == -1) {
2024-10-31 22:26:55 +00:00
printf("All brackets OK\n");
2024-10-31 18:46:23 +00:00
} else {
2024-10-31 19:02:33 +00:00
printf("Unmatched opening bracket %c\n", stack[top]);
2024-10-31 18:46:23 +00:00
}
2024-10-31 18:45:11 +00:00
}
int main() {
char code[100];
fgets(code, 100, stdin);
check_brackets(code);
return 0;
2024-10-31 19:02:33 +00:00
}