Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #include <iostream>
  2. #include <cctype>
  3.  
  4. enum { MAX_SIZE = 1000 };
  5. char *x;
  6.  
  7.  
  8. void inc_exp(){
  9. std::cout << "ERROR: incorrect expression.\n";
  10. std::exit(1);
  11. }
  12.  
  13.  
  14. int parseFactor() {
  15. while (isspace(*x)) {
  16. x++;
  17. }
  18. int value = 0, sign = 1;
  19. if (*x == '+' || *x == '-') {
  20. if (*x == '-') {
  21. sign = -1;
  22. }
  23. x++;
  24. }
  25. while (isspace(*x)) {
  26. x++;
  27. }
  28. if (isdigit(*x)) {
  29. while (isdigit(*x)) {
  30. value = value * 10 + *x - '0';
  31. x++;
  32. }
  33. return sign * value;
  34. }
  35. else {
  36. inc_exp();
  37. }
  38. }
  39.  
  40. int parseMultDiv() {
  41.  
  42. int fac1 = parseFactor();
  43.  
  44. while (*x == '*' || *x == '/') {
  45. char temp = *x;
  46. x++;
  47. int fac2 = parseFactor();
  48. if (temp == '*') {
  49. fac1 *= fac2;
  50. }
  51. else {
  52. if (fac2 == 0) inc_exp();
  53. fac1 /= fac2;
  54. }
  55.  
  56. }
  57. return fac1;
  58. }
  59.  
  60. int parseSumSub() {
  61.  
  62. int pro1 = parseMultDiv();
  63.  
  64. while (*x == '+' || *x == '-') {
  65. int sign = 1;
  66. if (*x == '-') sign = -1;
  67. ++x;
  68. int pro2 = parseMultDiv();
  69. pro1 = pro1 + sign * pro2;
  70.  
  71. }
  72. if (*x != '\0') {
  73. inc_exp();
  74. }
  75. return pro1;
  76. }
  77.  
  78. int main(int argc, char **argv) {
  79. char norm_exp[MAX_SIZE];
  80. x = norm_exp;
  81. if (argc == 1) {
  82. inc_exp();
  83. }
  84. for (int i = 1; i < argc; i++) {
  85. for (int j = 0; j < len(argc[i]); j++) {
  86. *x++ = argc[j];
  87. }
  88. }
  89. if (*(x - 1) != '\"' || norm_exp != '\"') {
  90. inc_exp();
  91. }
  92. *(x - 1) = '\0';
  93. x = norm_exp + 1;
  94. std::cout << parseSumSub();
  95. return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement