usaa24/a1/program.c

72 lines
1.8 KiB
C
Raw Normal View History

2024-10-24 10:20:55 +00:00
#include <stdio.h>
2024-10-24 12:23:37 +00:00
#include <stdlib.h>
2024-10-24 10:20:55 +00:00
#include <string.h>
2024-10-24 12:23:37 +00:00
#define MAX_LENGTH 100
2024-10-24 10:20:55 +00:00
2024-10-24 12:23:37 +00:00
int isMatching(char opening, char closing) {
return (opening == '{' && closing == '}') ||
(opening == '[' && closing == ']') ||
(opening == '(' && closing == ')') ||
(opening == '<' && closing == '>');
2024-10-24 10:20:55 +00:00
}
int main() {
2024-10-24 12:23:37 +00:00
char input[MAX_LENGTH + 1];
char stack[MAX_LENGTH];
int top = -1;
int position = 0;
printf("Zadajte kód (maximálne 100 znakov): ");
fgets(input, sizeof(input), stdin);
input[strcspn(input, "\n")] = 0;
if (strlen(input) > MAX_LENGTH) {
printf("Chyba: dĺžka reťazca presahuje 100 znakov.\n");
return 1;
}
2024-10-24 10:20:55 +00:00
2024-10-24 12:23:37 +00:00
printf("Načítané: %s\n", input);
2024-10-24 10:47:58 +00:00
2024-10-24 12:23:37 +00:00
for (int i = 0; i < strlen(input); i++) {
char current = input[i];
position++;
2024-10-24 10:20:55 +00:00
2024-10-24 12:23:37 +00:00
if (current == '{' || current == '[' || current == '(' || current == '<') {
stack[++top] = current; \
}
else if (current == '}' || current == ']' || current == ')' || current == '>') {
2024-10-24 10:28:31 +00:00
if (top == -1) {
2024-10-24 12:23:37 +00:00
printf("Neočekávaný znak %c na %d, očakávaná otváracia zátvorka.\n", current, position);
return 1;
2024-10-24 10:28:31 +00:00
}
2024-10-24 12:23:37 +00:00
if (!isMatching(stack[top--], current)) {
printf("Prekrývajúca sa zátvorka %c na %d, očakávaná %c.\n", current, position,
(current == '}') ? '{' : (current == ']') ? '[' :
(current == ')') ? '(' : '<');
return 1;
2024-10-24 10:20:55 +00:00
}
}
}
2024-10-24 12:23:37 +00:00
2024-10-24 10:20:55 +00:00
if (top != -1) {
2024-10-24 12:23:37 +00:00
printf("Neočekávaný koniec vstupu, očakávaná zatváracia zátvorka pre %c.\n", stack[top]);
return 1;
2024-10-24 10:20:55 +00:00
}
2024-10-24 12:23:37 +00:00
printf("Všetky zátvorky sú v poriadku\n");
return 0;
2024-10-24 10:20:55 +00:00
}