This commit is contained in:
Matej Hajduk 2025-10-21 19:00:44 +02:00
parent 3715d0936c
commit 96b50c9610

View File

@ -3,7 +3,6 @@
#define MAX 101 #define MAX 101
// vracia zodpovedajúcu zatváraciu zátvorku
char expected_close(char open) { char expected_close(char open) {
switch (open) { switch (open) {
case '(': return ')'; case '(': return ')';
@ -17,15 +16,13 @@ char expected_close(char open) {
int main(void) { int main(void) {
char line[MAX]; char line[MAX];
char stack[MAX]; char stack[MAX];
int pos[MAX]; // pozície otvorených zátvoriek (0-indexed) int pos[MAX];
int top = -1; int top = -1;
if (fgets(line, MAX, stdin) == NULL) if (fgets(line, MAX, stdin) == NULL)
return 0; return 0;
// odstrániť newline ak je prítomné
line[strcspn(line, "\n")] = '\0'; line[strcspn(line, "\n")] = '\0';
printf("Read: %s\n", line); printf("Read: %s\n", line);
int ok = 1; int ok = 1;
@ -37,11 +34,10 @@ int main(void) {
if (ch == '(' || ch == '{' || ch == '[' || ch == '<') { if (ch == '(' || ch == '{' || ch == '[' || ch == '<') {
top++; top++;
stack[top] = ch; stack[top] = ch;
pos[top] = i; // uložíme 0-indexovanú pozíciu pos[top] = i; // 0-indexovaná pozícia, may be used elsewhere
} }
else if (ch == ')' || ch == '}' || ch == ']' || ch == '>') { else if (ch == ')' || ch == '}' || ch == ']' || ch == '>') {
if (top < 0) { if (top < 0) {
// prázdny zásobník -> neočakávané zatvorenie, pozícia i (0-index)
printf("Unexpected closing bracket %c in %d\n", ch, i); printf("Unexpected closing bracket %c in %d\n", ch, i);
ok = 0; ok = 0;
break; break;
@ -50,7 +46,6 @@ int main(void) {
char last_open = stack[top]; char last_open = stack[top];
char expected = expected_close(last_open); char expected = expected_close(last_open);
if (ch != expected) { if (ch != expected) {
// prekríženie: reportujeme aktuálnu pozíciu i (0-index)
printf("Crossed bracket %c in %d, expected %c\n", ch, i, expected); printf("Crossed bracket %c in %d, expected %c\n", ch, i, expected);
ok = 0; ok = 0;
break; break;
@ -60,8 +55,13 @@ int main(void) {
} }
if (ok && top >= 0) { if (ok && top >= 0) {
// chýba zatváracia zátvorka pre poslednú otvorenú -- pozícia sa vypisuje 0-index // Vytvoríme reťazec všetkých chýbajúcich zatváracích zátvoriek v poradí, ktoré treba doplniť.
printf("Missing closing bracket for %c from %d\n", stack[top], pos[top]); printf("Missing closing brackets: ");
for (int i = top; i >= 0; i--) {
char c = expected_close(stack[i]);
if (c) putchar(c);
}
putchar('\n');
ok = 0; ok = 0;
} }