fork(3) download
  1. #include <iostream>
  2. #include <string>
  3. #include <string.h>
  4. #include <ctype.h>
  5.  
  6. bool n_expr (const char *&s, int &result);
  7. bool p_expr (const char *&s, int &result);
  8. bool o_expr (const char *&s, int &result, int eos);
  9.  
  10. bool expr (const char *&s, int &result, int eos = 0) {
  11. while (isspace(*s)) ++s;
  12. if (*s == eos) return false;
  13. if (isdigit(*s)) {
  14. if (!n_expr(s, result)) return false;
  15. } else if (*s == '(') {
  16. if (!p_expr(s, result)) return false;
  17. } else return false;
  18. while (isspace(*s)) ++s;
  19. if (*s == eos) return true;
  20. return o_expr(s, result, eos);
  21. }
  22.  
  23. bool n_expr (const char *&s, int &result) {
  24. int n = 0;
  25. while (isdigit(*s)) n = 10 * n + (*s++ - '0');
  26. result = n;
  27. return true;
  28. }
  29.  
  30. bool p_expr (const char *&s, int &result) {
  31. if (expr(++s, result, ')')) {
  32. ++s;
  33. return true;
  34. }
  35. return false;
  36. }
  37.  
  38. bool o_expr (const char *&s, int &result, int eos) {
  39. int oresult = 0;
  40. const char *op = strchr("+-*/", *s);
  41. if (op == 0) return false;
  42. if (!expr(++s, oresult, eos)) return false;
  43. switch (*op) {
  44. case '+': result += oresult; break;
  45. case '-': result -= oresult; break;
  46. case '*': result *= oresult; break;
  47. case '/': result /= oresult; break;
  48. default: return false;
  49. }
  50. return true;
  51. }
  52.  
  53. int main() {
  54. std::string buf;
  55. const char *p;
  56. int r;
  57. while (std::getline(std::cin, buf)) {
  58. if (expr(p = buf.c_str(), r)) {
  59. std::cout << r << std::endl;
  60. } else {
  61. std::cout << "ERROR\n";
  62. }
  63. }
  64. return 0;
  65. }
Runtime error #stdin #stdout 0s 3436KB
stdin
4/2+2
2/2/10
stdout
1