栈  0.1
数据结构_第3章
ch3_5.cc
Go to the documentation of this file.
1 
12 #include "Rpn.hh"
13 #include <cstring>
14 #include <ctime>
15 
16 int main(int argc, char const *argv[])
17 {
18  // time
19  clock_t t = clock();
20  time_t rawtime;
21  struct tm *timeinfo;
22 
23  time(&rawtime); // Get the current calendar time
24  timeinfo = localtime(&rawtime); // Convert time_t to tm as local time
25  printf("Current local time and date: %s\n", asctime(timeinfo)); // Convert tm structure to string
26 
27  // configure: 命令行输入arg2为-p, 表示arg1为RPN
28  bool isPostExpr = (argc > 2 && !strcmp(argv[2], "-p"));
29 
30  try
31  {
32  if (argc > 1)
33  {
34  if (isPostExpr) // 用户输入后缀式
35  {
37  std::cout << "Postfix: " << rpn.postfix() << '\n';
38  std::cout << "Result: " << rpn.calcVal() << std::endl;
39  return 0;
40  }
41 
42  // 若用户输入中缀式
43  // 先转为后缀式string
44  std::string _postfix = RPN::Rpn_t(argv[1]).postfix();
45  std::cout << "Postfix: " << _postfix << '\n';
46 
47  // 用后缀string构造新对象, 并求值
48  std::cout << "Result: " << RPN::Rpn_t(_postfix, RPN::notationType::Postfix).calcVal() << std::endl;
49 
50  t = clock() - t;
51  printf("\nIt took me %ld clicks (%f seconds).\n", t, ((float)t) / CLOCKS_PER_SEC);
52  return 0;
53  }
54 
55  std::string infixStr1{"(5+6^2*(7+3)/3)/4+5"};
56  std::cout << "\nInfix: " << infixStr1 << '\n';
57 
58  RPN::Rpn_t rpn(infixStr1); // 用中缀string构造对象
59  std::cout << "Postfix: " << rpn.postfix() << '\n'; // 输出转换得到的后缀string
60  rpn.assign(rpn.postfix(), RPN::notationType::Postfix); // 用后缀string修改对象
61  std::cout << "Result: " << rpn.calcVal() << std::endl; // 输出表达式的值
62 
63  // 用户交互地输入后缀式
64  char expr[RPN::buf_size];
65  do
66  {
67  std::cout << "Input postfix notation: ";
68  std::cin.getline(expr, RPN::buf_size, '\n');
69  if (!std::cin.fail())
70  break;
71 
72  std::cin.clear();
73  std::cin.sync();
74  } while (true);
75 
76  std::cout << "\nPostfix: " << expr << '\n';
77  std::cout << "Result: " << rpn.assign(expr, RPN::notationType::Postfix).calcVal() << std::endl;
78  }
79  catch (const std::exception &e)
80  {
81  std::cerr << e.what() << '\n';
82  }
83 
84  t = clock() - t;
85  printf("\nIt took me %ld clicks (%f seconds).\n", t, ((float)t) / CLOCKS_PER_SEC);
86 
87  return 0;
88 }
RPN::buf_size
const int buf_size
项的最大长度 = buf_size - 1
Definition: Rpn.hh:32
main
int main(int argc, char const *argv[])
Definition: ch3_5.cc:16
RPN::notationType::Postfix
@ Postfix
后缀表达式
RPN::Rpn_t::calcVal
double calcVal() const
计算(后缀)表达式的值
Definition: Rpn.hh:587
RPN::Rpn_t::postfix
std::string postfix() const
获取后缀形式的string
Definition: Rpn.hh:421
RPN::Rpn_t
Definition: Rpn.hh:126
RPN::Rpn_t::assign
Rpn_t & assign(const std::string &expr_str, notationType _type=notationType::Infix)
设置Rpn_t类对象的值
Definition: Rpn.hh:396
Rpn.hh
后缀表达式类