# 華為筆試——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 }```

0条回复