7
This commit is contained in:
parent
a8d85d812d
commit
23cf99cf01
22
a1/program.c
22
a1/program.c
@ -10,9 +10,14 @@ int is_matching_pair(char open, char close) {
|
|||||||
(open == '<' && close == '>');
|
(open == '<' && close == '>');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
char matching_close(char open) {
|
||||||
|
return open == '(' ? ')' :
|
||||||
|
open == '{' ? '}' :
|
||||||
|
open == '[' ? ']' : '>';
|
||||||
|
}
|
||||||
|
|
||||||
void check_brackets(const char *code) {
|
void check_brackets(const char *code) {
|
||||||
char stack[MAX_LEN];
|
char stack[MAX_LEN];
|
||||||
int positions[MAX_LEN];
|
|
||||||
int top = -1;
|
int top = -1;
|
||||||
|
|
||||||
printf("Read: %s\n", code);
|
printf("Read: %s\n", code);
|
||||||
@ -23,7 +28,6 @@ void check_brackets(const char *code) {
|
|||||||
if (ch == '(' || ch == '{' || ch == '[' || ch == '<') {
|
if (ch == '(' || ch == '{' || ch == '[' || ch == '<') {
|
||||||
if (top < MAX_LEN - 1) {
|
if (top < MAX_LEN - 1) {
|
||||||
stack[++top] = ch;
|
stack[++top] = ch;
|
||||||
positions[top] = i;
|
|
||||||
} else {
|
} else {
|
||||||
printf("Stack overflow at position %d\n", i);
|
printf("Stack overflow at position %d\n", i);
|
||||||
return;
|
return;
|
||||||
@ -35,10 +39,7 @@ void check_brackets(const char *code) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!is_matching_pair(stack[top], ch)) {
|
if (!is_matching_pair(stack[top], ch)) {
|
||||||
printf("Crossed bracket %c in %d, expected %c\n", ch, i,
|
printf("Crossed bracket %c in %d, expected %c\n", ch, i, matching_close(stack[top]));
|
||||||
stack[top] == '(' ? ')' :
|
|
||||||
stack[top] == '{' ? '}' :
|
|
||||||
stack[top] == '[' ? ']' : '>');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
top--;
|
top--;
|
||||||
@ -46,10 +47,11 @@ void check_brackets(const char *code) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (top != -1) {
|
if (top != -1) {
|
||||||
printf("Missing closing brackets: %c\n",
|
printf("Missing closing brackets: ");
|
||||||
stack[top] == '(' ? ')' :
|
while (top != -1) {
|
||||||
stack[top] == '{' ? '}' :
|
printf("%c", matching_close(stack[top--]));
|
||||||
stack[top] == '[' ? ']' : '>');
|
}
|
||||||
|
printf("\n");
|
||||||
} else {
|
} else {
|
||||||
printf("All brackets OK\n");
|
printf("All brackets OK\n");
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user