[刷题] PTA 7-62 切分表达式 写个tokenizer吧

我的程序:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #define N 50
 4 char token[]= {'+','-','*','/','(',')'};
 5 
 6 int istoken(char c) {
 7     int i;
 8     for(i=0; i<strlen(token); i++) {
 9         if(token[i]==c) return 1;
10     }
11     return 0;
12 }
13 
14 int main() {
15     int i,j,t=0,flag=0;
16     char s[N],temp[N];
17     scanf("%s",s);
18     int len = strlen(s);
19     for(i=0; i<len; i++) {
20         //如果是减号且前面也是符号,则将减号作为后面数据的一部分
21         if((i==0 && s[i]=='-')||(istoken(s[i-1]) && s[i]=='-')) flag = 1;
22         //如果是符号,且不是上面的情况,则先打印符号前的数据,再打印符号
23         if(istoken(s[i]) && flag==0) {
24             for(j=0; j<t; j++) {
25                 printf("%c",temp[j]);
26             }
27             //运算符紧跟括号时,不输出回车 
28             if(t!=0)
29                 printf("
");
30             t=0;
31             //如果到末尾,则不输出回车
32             printf("%c",s[i]);
33             if(i!=len-1)
34                 printf("
");
35         } else {
36             temp[t]=s[i];
37             t++;
38             //flag清零
39             flag = 0;
40             //输出末尾的数据
41             if(i==len-1) {
42                 for(j=0; j<t; j++) {
43                     printf("%c",temp[j]);
44                 }
45             }
46         }
47     }
48 }

(最后一个用例提示“格式错误”,没有找出bug)

网友“扯淡”的程序:

 1 #include <stdio.h>
 2 #include <string.h>
 3 int main(){
 4     char str[41], ch, flag=0;
 5     int i=0;
 6     scanf("%s", str);
 7     int len=strlen(str);
 8     printf("%c", str[0]);
 9     for(i=1; i<len; i++){
10         if (str[i]>47 && str[i]<58 || str[i]=='.'){
11             if (flag)
12                 printf("
");
13             printf("%c", str[i]);
14             flag=0;
15         }else{
16             if (str[i-1]=='(' && str[i]=='-'){
17                 printf("
%c", str[i]);
18                 flag=0;
19             }else{
20                 printf("
%c", str[i]);
21                 flag=1;
22             }
23         }
24     }
25     return(0);
26 } 

https://blog.csdn.net/qq_36589706/article/details/81081144

分析:

1、我是一开始就想的比较复杂,然后在测试中不断补漏洞;扯淡是一开始就想的很简单,只分成数值和非数值两种情况

2、程序构造的越抽象,细节越少,越不容易出错

3、从计算机的角度,而不是实际意义的角度出发思考问题

原文地址:https://www.cnblogs.com/cxc1357/p/10813023.html