/* Program: tokenization.c (Report comments/bugs to chikh@yuntech.edu.tw) Function: 輸入運算相關的文字串,從中提取關鍵資訊,為作業的預備暖身 Notes: 輸入可為 w={"Mary":10, "Tom":3, "Charlie":5, "Bob":6, "Dickens":20, 4:9, "z":0, "Za":12, "aZ":8} del w["Dickens"] w["Mary"]=1 w["Tom"]+=2 w[4]? w? */ #include /* for sscanf(), printf() */ #include /* for strstr(), strtok(), strtok_r() */ int main() { char *token, key[12], line[128]; const char *s = " ={},"; /* 分隔符記的字元 */ int value, i = 0; char *rest; printf("\n*** 從字串讀取符記(token)程式 ***\n\n輸入存取字典的陳述,逕按結束程式\n"); while (1) { printf("\n指令 => "); fgets(line,128,stdin); /* 使用gets()讀取也可以,但因gets()未設讀入字元數的限制,可能導致儲存輸入字元的陣列空間爆掉 */ if (line[0]=='\n') break; /* 輸入空字串則跳離此迴圈 */ if (strstr(line,"{")) { /* line含有"{" */ sscanf(line,"w = {%[^}]}",line); /* printf("大括弧內字串 %s\n",line); */ rest = line; while (token = strtok_r(rest,s,&rest)) { /* strtok_r()的用法可參見 http://bit.ly/3VcvbbZ */ /* printf("%s\n",token); */ if (strstr(token,":")) {/* token含有":" */ sscanf(token,"%[^:]:%d",key,&value); printf("Token #%d: 鍵=%s; 值=%d\n",++i,key,value); } } } else if (strstr(line,"del")) { /* line含有"del" */ sscanf(line,"del w[%[^]]]",key); printf("刪除運算:鍵=%s\n",key); } else if (strstr(line,"+=")) { /* line含有"+=" */ sscanf(line,"w[%[^]]] +=%d",key,&value); printf("遞增運算:鍵=%s;運算元=%d\n",key,value); } else if (strstr(line,"=")) { /* line含有"=" */ sscanf(line,"w[%[^]]] = %d",key,&value); printf("指派運算:鍵=%s; 運算元=%d\n",key,value); } else if (sscanf(line,"w[%[^]]]?",key)==1) printf("讀值運算:鍵=%s\n",key); else if (strstr(line,"?")) printf("顯示整個字典內容(請同學實作,此為作業的一部分)\n"); else printf("語法無法辨認,sorry!\n"); } printf("\n程式結束,bye ~\n"); return 0; }