usaa24/a1/program.c

90 lines
2.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 100
// Function to check if two brackets are matching
int isMatching(char opening, char closing) {
return (opening == '{' && closing == '}') ||
(opening == '[' && closing == ']') ||
(opening == '(' && closing == ')') ||
(opening == '<' && closing == '>');
}
// Function to get the expected closing bracket for a given opening bracket
char getExpectedClosingBracket(char opening) {
return (opening == '{') ? '}' :
(opening == '[') ? ']' :
(opening == '(') ? ')' :
(opening == '<') ? '>' : '\0';
}
int main() {
char input[MAX_LENGTH + 1];
char stack[MAX_LENGTH];
int top = -1; // Stack pointer
int position = -1; // Start position at -1 to adjust to 0-based indexing
int foundBracket = 0; // Flag to check if any bracket is found
// Reading the string
fgets(input, sizeof(input), stdin);
// Remove newline character if present
input[strcspn(input, "\n")] = 0;
// Check if string length exceeds MAX_LENGTH
if (strlen(input) > MAX_LENGTH) {
printf("Chyba: dĺžka reťazca presahuje 100 znakov.\n");
return 1;
}
// Iterating over each character in the string
for (int i = 0; i < strlen(input); i++) {
char current = input[i];
position++;
// Check if current character is an opening bracket
if (current == '{' || current == '[' || current == '(' || current == '<') {
stack[++top] = current; // Push to stack
foundBracket = 1; // Found at least one bracket
}
// If current character is a closing bracket
else if (current == '}' || current == ']' || current == ')' || current == '>') {
// If stack is empty, it's an error
if (top == -1) {
printf("Read: %s\n", input);
printf("Unexpected closing bracket %c in %d\n", current, position);
return 0;
}
// If brackets do not match, it's an error
if (!isMatching(stack[top--], current)) {
printf("Read: %s\n", input);
printf("Crossed bracket %c in %d, expected %c.\n", current, position,
getExpectedClosingBracket(stack[top + 1]));
return 0;
}
}
}
// If there are unmatched opening brackets left in the stack
if (top != -1) {
printf("Read: %s\n", input);
printf("Missing closing brackets: %c\n", getExpectedClosingBracket(stack[top]));
return 0;
}
// If no brackets are found, output a success message
if (!foundBracket) {
printf("Read: %s\n", input);
printf("All brackets OK\n");
} else {
// Expected correct output if all brackets match
printf("Read: %s\n", input);
printf("All brackets OK\n");
}
return 0;
}