1 #include <stdio.h> 2 #include <string.h> 3 4 char prog[100],token[8],ch; 5 int syn,p,m,n,sum; 6 char *rwtab[6]={"begin","if","then","while","do","end"}; 7 8 void scaner(void); 9 10 main() 11 { 12 p=0; 13 printf(" 在下方输入你的字符串(按回车结束输入): "); 14 15 do{ 16 scanf("%c",&ch); 17 prog[p++]=ch; 18 }while(ch!=' '); 19 20 p=0; 21 do{ 22 scaner(); 23 switch(syn) 24 { 25 case 11: 26 printf("( %-10d%5d ) ",sum,syn); 27 break; 28 29 case -1: 30 printf("you have input a wrong string "); 31 return 0; 32 break; 33 34 default: 35 printf("( %-10s%5d ) ",token,syn); 36 break; 37 } 38 }while(syn!=0); 39 40 } 41 42 void scaner(void) 43 { 44 sum=0; 45 46 for(m=0;m<8;m++) 47 token[m++]= NULL; 48 49 ch=prog[p++]; 50 m=0; 51 52 while((ch==' ')||(ch==' ')) 53 ch=prog[p++]; 54 55 if(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A'))) 56 { 57 while(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A'))||((ch>='0')&&(ch<='9'))) 58 { 59 token[m++]=ch; 60 ch=prog[p++]; 61 } 62 63 p--; 64 syn=10; 65 66 for(n=0;n<6;n++) 67 if(strcmp(token,rwtab[n])==0) 68 { 69 syn=n+1; 70 break; 71 } 72 } 73 else if((ch>='0')&&(ch<='9')) 74 { 75 while((ch>='0')&&(ch<='9')) 76 { 77 sum=sum*10+ch-'0'; 78 ch=prog[p++]; 79 } 80 p--; 81 syn=11; 82 } 83 else 84 { 85 switch(ch) 86 { 87 case '<': 88 token[m++]=ch; 89 ch=prog[p++]; 90 if(ch=='=') 91 { 92 syn=21; 93 token[m++]=ch; 94 } 95 else 96 { 97 syn=20; 98 p--; 99 } 100 break; 101 102 case '>': 103 token[m++]=ch; 104 ch=prog[p++]; 105 if(ch=='=') 106 { 107 syn=24; 108 token[m++]=ch; 109 } 110 else 111 { 112 syn=23; 113 p--; 114 } 115 break; 116 117 case '+': 118 syn=13; 119 token[m++]=ch; 120 break; 121 122 case '-': 123 syn=14; 124 token[m++]=ch; 125 break; 126 127 case '=': 128 syn=25; 129 token[m++]=ch; 130 break; 131 132 case '*': 133 syn=15; 134 token[m++]=ch; 135 break; 136 137 case '/': 138 syn=16; 139 token[m++]=ch; 140 break; 141 142 case '(': 143 syn=27; 144 token[m++]=ch; 145 break; 146 147 case ')': 148 syn=28; 149 token[m++]=ch; 150 break; 151 152 case '<>': 153 syn=22; 154 token[m++]=ch; 155 break; 156 157 case ';': 158 syn=26; 159 token[m++]=ch; 160 break; 161 162 case '#': 163 syn=0; 164 token[m++]=ch; 165 break; 166 167 case ':': 168 token[m++]=ch; 169 ch=prog[p++]; 170 if(ch=='=') 171 { 172 syn=18; 173 token[m++]=ch; 174 } 175 else 176 { 177 syn=17; 178 token[m++]=ch; 179 } 180 break; 181 182 default: 183 syn=-1; 184 break; 185 } 186 } 187 token[m++]='