Update 'a1/program.c'

This commit is contained in:
Anzhelika Nikolaieva 2023-10-31 16:03:53 +00:00
parent 7f2b626453
commit 8fa4756238

View File

@ -1,71 +1,64 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <stdbool.h> #include <stdbool.h>
#include<ctype.h>
int open_brackets(char a) { bool brackets(const char *code) {
return (a == '(' || a == '[' || a == '{' || a == '<'); int stack[100];
} int top = -1;
int close_brackets(char a) { for (int i = 0; code[i] != '\0'; i++) {
return (a == ')' || a == ']' || a == '}' || a == '>'); if (code[i] == '(' || code[i] == '[' || code[i] == '{' || code[i] == '<') {
} stack[++top] = i;
} else if (code[i] == ')' || code[i] == ']' || code[i] == '}' || code[i] == '>') {
char brackets(char a) { if (top == -1) {
switch (a) { printf("Unexpected closing bracket %c in %d \n", code[i], i);
case ')': return false;
return '(';
case ']':
return '[';
case '}':
return '{';
case '>':
return '<';
default:
return '\0';
} }
int opening = stack[top--];
char expected_opening = 0;
if (code[i] == ')') {
expected_opening = '(';
} else if (code[i] == ']') {
expected_opening = '[';
} else if (code[i] == '}') {
expected_opening = '{';
} else if (code[i] == '>') {
expected_opening = '<';
}
if (code[opening] != expected_opening) {
printf("Crossed bracket %c in %d, expected %c \n", code[i], i, expected_opening);
return false;
}
}
}
if (top != -1) {
int opening = stack[top];
printf("Unclosed bracket %c in %d \n", code[opening], opening);
return false;
}
return true;
} }
int main() { int main() {
char code[100]; char code[100];
printf("Read: ");
fgets(code, sizeof(code), stdin); fgets(code, sizeof(code), stdin);
int stack[100]; if (code[strlen(code) - 1] == '\n') {
int skobochka = -1; code[strlen(code) - 1] = '\0';
int error = -1;
char letters[100];
int letter_i = 0;
for (int i = 0; code[i] != '\0'; i++) {
if (isalpha(code[i])) {
printf("%c", code[i]);
letters[letter_i++] = code[i];
}
if (open_brackets(code[i])) {
printf(" ");
stack[++skobochka] = i;
} else if (close_brackets(code[i])) {
printf("%c", code[i]);
if (skobochka == -1) {
error = i;
break;
}
if (code[stack[skobochka]] != brackets(code[i])) {
error = i;
break;
}
skobochka--;
}
} }
if (error == -1 && skobochka == -1) { printf("Read: %s\n", code);
printf("\nAll brackets OK\n");
} else if (error == -1) { if (brackets(code)) {
printf("\nClosing bracket at position %d is not paired\n", stack[skobochka]); printf("All brackets OK\n");
} else {
printf("\nUnexpected closing bracket %c in %d\n", code[error], error);
} }
return 0; return 0;
} }