t1nman

lab3_1

May 22nd, 2012
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include "mystack.h"
  3.  
  4. void polska(char ar1[], char ar2[]);
  5.  
  6. main()
  7. {
  8.     char infix[SIZE], postfix[SIZE];
  9.     FILE *ifp, *ofp;
  10.     int i = 0;
  11.  
  12.     ifp = fopen("input.txt", "r");
  13.  
  14.     while ( !feof(ifp) ) {
  15.         fscanf(ifp, "%c", &infix[++i]);
  16.     }
  17.  
  18.     fclose(ifp);
  19.  
  20.     infix[0] = i;
  21.  
  22.     polska(infix, postfix);
  23.  
  24.     ofp = fopen("output.txt", "w");
  25.  
  26.     for (i = 1; i <= postfix[0]; i++) {
  27.         fprintf(ofp, "%c ", postfix[i]);
  28.     }
  29.  
  30.     fprintf(ofp, "\n");
  31.    
  32.     fclose(ofp);
  33.  
  34.     return 0;
  35. }
  36.  
  37. int prior(char sign)
  38. {
  39.     switch(sign) {
  40.         case '*':case '/': return 2;
  41.                            break;
  42.         case '+':case '-': return 1;
  43.                            break;
  44.     }
  45.  
  46.     return 0;
  47. }
  48.  
  49. void polska(char inf[], char post[])
  50. {
  51.     Stack S;
  52.     int i, j = 0;
  53.     char curr_char, smbl;
  54.  
  55.     init(&S);
  56.  
  57.     for (i = 1; i <= inf[0]; i++) {
  58.         switch ( curr_char = inf[i] ) {
  59.             case '0':case '1':case '2':case '3':case '4':case '5':
  60.             case '6':case '7':case '8':case '9':
  61.                 post[++j] = curr_char;
  62.                 break;
  63.  
  64.             case '+':case '-':case '*':case '/':
  65.                 if ((empty(&S) == 1) || (prior(curr_char) > prior(showtop(&S))))
  66.                     push(&S, curr_char);
  67.                 else {
  68.                         while (prior(curr_char) <= prior(showtop(&S)))
  69.                             post[++j] = pop(&S);
  70.                         push(&S, curr_char);
  71.                 }
  72.                 break;
  73.  
  74.             case '(': push(&S, curr_char);
  75.                       break;
  76.  
  77.             case ')': while ( (smbl = pop(&S)) != '(' ) {
  78.                           post[++j] = smbl;
  79.                       }
  80.                       break;
  81.             default:  break;
  82.         }
  83.     }
  84.  
  85.     while ( empty(&S) != 1)
  86.         post[++j] = pop(&S);
  87.    
  88.     post[0] = j;
  89.    
  90.     return;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment