### 华为笔试——C++字符串四则运算的实现

``` 1 #include <iostream>
2 #include <string>
3 using namespace std;
4 int main()
5 {
6     int i = 0;
7     string str;
8     cin >> str;
9     int n = str.length();
10     char *num = new char[n];
11     strcpy(num, str.c_str());
12     //char num[10] = "8+7*2-9/3";
13     int num2[15] = {0};
14     for (i=0;i<n;i++)
15     {
16         if (num[i] >= '0'&&num[i] <= '9')
17         {
18             num2[i] = num[i]-48;//char转换成int
19         }
20     }
21     for (i = 0; i < n; i++)
22     {
23         if (num[i] == '*')
24         {
25             num2[i - 1] = num2[i - 1] *num2[i + 1];
26             for (int j = i; j <(n-2); j++)
27             {
28                 num[j] = num[j + 2];//长度-2
29                 num2[j] = num2[j + 2];
30             }
31         }
32         if (num[i] == '/')
33         {
34             num2[i - 1] = num2[i - 1] /num2[i + 1];
35             for (int j = i; j <(n-2); j++)
36             {
37                 num[j] = num[j + 2];//长度-2
38                 num2[j] = num2[j + 2];
39             }
40         }
41     }
42     for (i = 0; i < n; i++)
43     {
44         if (num[i] == '+')
45         {
46             num2[i - 1] = num2[i - 1]+num2[i + 1];
47             for (int j = i; j <(n-2); j++)
48             {
49                 num[j] = num[j + 2];//长度-2
50                 num2[j] = num2[j + 2];
51             }
52         }
53         if (num[i] == '-')
54         {
55             num2[i - 1] = num2[i - 1] -num2[i + 1];
56             for (int j = i; j <(n-2); j++)
57             {
58                 num[j] = num[j + 2];//长度-2
59                 num2[j] = num2[j + 2];
60             }
61         }
62     }
63     cout << num2[0] << endl;
64     return 0;
65 }```

 变量名|  i 0 1 2 3 4 5 6 7 8 num 8 + 7 * 2 - 9 / 3 num2 8 0 7 0 2 0 9 0 3

 变量名| i 0 1 2 3 4 5 6 7 8 num 8 + 7 - 9 / 3 / 3 num2 8 0 14 0 9 0 3 0 3

 变量名| i 0 1 2 3 4 5 6 7 8 num 8 + 7 - 9 / 3 / 3 num2 8 0 14 0 3 0 3 0 3