APL/Révisions/CM/parenthesage.c

34 lines
917 B
C
Raw Permalink Normal View History

2022-01-25 12:00:33 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
if (argc < 2) {
puts("Veuillez préciser une expression arithmétique...");
return EXIT_FAILURE;
}
char* result = (char*)calloc(strlen(argv[1])+1, sizeof(char));
int length = 0, nb_ouvrante = 0, nb_fermante = 0;
for (int i = 0; i < strlen(argv[1]); i++) {
if (argv[1][i] == '(' || argv[1][i] == ')') {
result[length] = argv[1][i];
length++;
if (argv[1][i] == '(') nb_ouvrante++;
else nb_fermante++;
}
}
int equite = 0;
for (int i = 0; i < strlen(result); i++) {
if (result[i] == '(') equite++;
else equite--;
if (equite < 0) break;
}
printf("%s %s %s\n", result, nb_ouvrante == nb_fermante ? "OK" : "NOK", equite == 0 ? "valide" : "non valide");
return EXIT_SUCCESS;
}