usaa24/a1/program.c

64 lines
1.6 KiB
C

#include <stdio.h>
#include <string.h>
int isOpening(char c) {
return c == '{' || c == '[' || c == '(' || c == '<';
}
int isClosing(char c) {
return c == '}' || c == ']' || c == ')' || c == '>';
}
int isMatching(char open, char close) {
return (open == '{' && close == '}') ||
(open == '[' && close == ']') ||
(open == '(' && close == ')') ||
(open == '<' && close == '>');
}
int main() {
char input[101];
char stack[100];
int top = -1;
// printf("");
fgets(input, 101, stdin);
printf("Read: %s", input);
for (int i = 0; i < strlen(input); i++) {
char current = input[i];
if (isOpening(current)) {
if (top < 99) {
stack[++top] = current;
} else {
printf("Stack is full\n");
return 1;
}
} else if (isClosing(current)) {
if (top == -1) {
printf("Unexpected closing bracket '%c' in %d.\n", current, i);
return 1;
}
if (!isMatching(stack[top], current)) {
printf("Crossed bracket '%c' in %d , expected \n", current, i);
(stack[top] == '{') ? '}' :
(stack[top] == '[') ? ']' :
(stack[top] == '(') ? ')' : '>',
current, i;
return 1;
}
top--;
}
}
if (top != -1) {
printf("Unexpected opennig bracket\n");
return 1;
}
printf("All brackets OK\n");
return 0;
}