s
This commit is contained in:
parent
9d79f9d77b
commit
d14a4c9508
15
a1/program.c
15
a1/program.c
@ -6,11 +6,19 @@ int match(char open, char close) {
|
|||||||
(open == '(' && close == ')') || (open == '<' && close == '>');
|
(open == '(' && close == ')') || (open == '<' && close == '>');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
char expected_closing(char open) {
|
||||||
|
if (open == '{') return '}';
|
||||||
|
if (open == '[') return ']';
|
||||||
|
if (open == '(') return ')';
|
||||||
|
if (open == '<') return '>';
|
||||||
|
return '\0';
|
||||||
|
}
|
||||||
|
|
||||||
void check_brackets(const char *code) {
|
void check_brackets(const char *code) {
|
||||||
char stack[100];
|
char stack[100];
|
||||||
int top = -1;
|
int top = -1;
|
||||||
|
|
||||||
printf("Read: %s\n", code);
|
printf("Read: %s\n", code);
|
||||||
|
|
||||||
for (int i = 0; code[i] != '\0'; i++) {
|
for (int i = 0; code[i] != '\0'; i++) {
|
||||||
char c = code[i];
|
char c = code[i];
|
||||||
@ -22,18 +30,19 @@ void check_brackets(const char *code) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!match(stack[top], c)) {
|
if (!match(stack[top], c)) {
|
||||||
printf("Crossed bracket %c in %d, expected %c\n", c, i, stack[top]);
|
printf("Crossed bracket %c in %d, expected %c\n", c, i, expected_closing(stack[top]));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
top--;
|
top--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (top == -1) {
|
if (top == -1) {
|
||||||
printf("All brackets OK\n");
|
printf("All brackets OK\n");
|
||||||
} else {
|
} else {
|
||||||
printf("Missing closing brackets: ");
|
printf("Missing closing brackets: ");
|
||||||
while (top >= 0) {
|
while (top >= 0) {
|
||||||
printf("%c", stack[top--]);
|
printf("%c", expected_closing(stack[top--]));
|
||||||
}
|
}
|
||||||
printf("\n");
|
printf("\n");
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user