Advertisement
Guest User

Untitled

a guest
Oct 13th, 2015
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.85 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. int validateExpression(char*);
  6. double parseExpression(char*);
  7. void removeAt(char*, int);
  8.  
  9. int main(int argc, char **argv) {
  10.  
  11.     char *exp;
  12.  
  13.     if(argc != 2) {
  14.         printf("Error\nFormat : super_calculator \"...expression...\"\n");
  15.         return 1;
  16.     }
  17.  
  18.     exp = argv[1];
  19.  
  20.     if(!validateExpression(exp)) {
  21.         printf("Expression not valid !\n");
  22.     }
  23.  
  24.     double result = parseExpression(exp);
  25.  
  26.     printf("%f", result);
  27.     return 0;
  28. }
  29.  
  30. int validateExpression(char *exp) {
  31.     unsigned int i, openBrackets = 0, closeBrackets = 0;
  32.     for(i = 0; i < strlen(exp); i++) {
  33.         exp[i] == '(' ? openBrackets++ : 1;
  34.         exp[i] == ')' ? closeBrackets++ : 1;
  35.     }
  36.     return (openBrackets == closeBrackets) && i; // i contains actual length of exp
  37. }
  38.  
  39. double parseExpression(char *exp) {
  40.     unsigned int i, j, lastPos, openBrackets = 0, closeBrackets = 0;
  41.     char *secondExp = NULL;
  42.     for(i = 0; i < strlen(exp); i++) {
  43.         if(exp[i] == '(') {
  44.             // Let's find the corresponding ')' in exp
  45.             openBrackets++;
  46.             j = i + 1 ;
  47.             while(openBrackets != closeBrackets) {
  48.                 exp[j] == '(' ? openBrackets++ : 1;
  49.                 exp[j] == ')' ? closeBrackets++ : 1;
  50.                 j++;
  51.             }
  52.             lastPos = j - 1;
  53.             secondExp = (char*) malloc(lastPos - i + 1);
  54.             memset(secondExp, '\0', lastPos - i + 1);
  55.             memcpy(secondExp, exp + i + 1, lastPos - i - 1);
  56.             printf("%s\n", secondExp);
  57.         }
  58.     }
  59.     if(secondExp != NULL) free(secondExp);
  60.     return 0;
  61. }
  62.  
  63. void removeAt(char *str, int pos) {
  64.     char *src, *dst;
  65.     for (src = dst = str; *src != '\0'; src++) {
  66.         *dst = *src;
  67.         if (*dst != pos) dst++;
  68.     }
  69.     *dst = '\0';
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement