1 #include<stdio.h> 2 #include<string.h> 3 4 int main() 5 { 6 char a[100] = "1+2=;3-2=;2*5=;8/4=;" ; 7 char b[100] = {0}; 8 char *s; 9 s = strtok(a, ";"); 10 while(s) 11 { 12 13 int i,j; 14 char c; 15 sscanf(s, "%d%c%d=", &i, &c, &j); 16 int res = 0; 17 switch(c) 18 { 19 case ‘+‘: 20 res = i + j; 21 break; 22 23 case ‘-‘: 24 res = i - j; 25 break; 26 27 case ‘*‘: 28 res = i * j; 29 break; 30 31 case ‘/‘: 32 res = i / j; 33 break; 34 default : 35 res = 0; 36 37 } 38 39 char tmp[100] = {0}; 40 sprintf(tmp, "%s%d;", s, res); //把运算式放入到tmp数组 41 strcat(b, tmp); //tmp是在循环内定义的,因此要在循环外再定义一个b 42 s = strtok(NULL, ";"); 43 44 } 45 46 strcpy(a, b); 47 printf("%s",a); 48 return 0; 49 50 }
原文地址:https://www.cnblogs.com/yangxiaoqin/p/8371754.html
时间: 2024-10-22 12:00:29