C:把算术表达式分成Token
2024-08-29 03:21:19
代码:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h> typedef enum{
TT_NUMBER,
TT_ADD,
TT_SUB,
TT_MUL,
TT_DIV,
TT_EOL
}TokenType; typedef struct{
TokenType type;
char text[];
}Token; static int pos=;
static char* line; void getToken(Token *token){
char arr[];
int index=;
arr[index]='\0'; while(line[pos]!='\0'){
if(line[pos]=='+'){
if(strlen(arr)>){
strcpy(token->text,arr);
index=;
arr[index]='\0';
token->type=TT_NUMBER; return;
} token->text[]='+';
token->text[]='\0';
token->type=TT_ADD;
pos++;
return;
}else if(line[pos]=='-'){
if(strlen(arr)>){
strcpy(token->text,arr);
index=;
arr[index]='\0';
token->type=TT_NUMBER;
return;
} token->text[]='-';
token->text[]='\0';
token->type=TT_SUB;
pos++;
return;
}else if(line[pos]=='*'){
if(strlen(arr)>){
strcpy(token->text,arr);
index=;
arr[index]='\0';
token->type=TT_NUMBER;
return;
} token->text[]='*';
token->text[]='\0';
token->type=TT_MUL;
pos++;
return;
}else if(line[pos]=='/'){
if(strlen(arr)>){
strcpy(token->text,arr);
index=;
arr[index]='\0';
token->type=TT_NUMBER;
return;
} token->text[]='/';
token->text[]='\0';
token->type=TT_DIV;
pos++;
return;
}else if(line[pos]=='\n'){
if(strlen(arr)>){
strcpy(token->text,arr);
index=;
arr[index]='\0';
token->type=TT_NUMBER;
return;
} token->text[]='\0';
token->type=TT_EOL;
pos++;
return;
}else{
arr[index]=line[pos];
index++;
arr[index]='\0';
pos++;
}
} if(strlen(arr)>){
strcpy(token->text,arr);
index=;
arr[index]='\0';
token->type=TT_NUMBER;
return;
}
} char* getTokenTypeDesc(Token *token){
char* arr;
arr = (char *)malloc(); if(token->type==){
strcpy(arr,"Num");
}else if(token->type==){
strcpy(arr,"Add");
}else if(token->type==){
strcpy(arr,"Sub");
}else if(token->type==){
strcpy(arr,"Mul");
}else if(token->type==){
strcpy(arr,"Div");
} return arr;
} void parse(){
Token token;
for(;;){
getToken(&token); if(token.type==TT_EOL){
break;
}else{
printf("%d %s %s\n",token.type, getTokenTypeDesc(&token) ,token.text);
}
}
} int _tmain(int argc, _TCHAR* argv[])
{
char buf[]; while(fgets(buf,,stdin)!=NULL){
pos=;
line=buf;
parse();
}
return ;
}
运行结果:
*+/-+
Num
Mul *
Num
Add +
Num
Div /
Num
Sub -
Num
Add +
Num
+
Num
Add +
Num
--2020年6月6日--
最新文章
- SCNU 2015ACM新生赛初赛【1001~1011】个人解题思路
- wpf打开文夹和打开文件
- angular的promise理解
- (转)The Neural Network Zoo
- Javaweb -- ServletContextListener
- 学习使用 jQuery &; CSS3 制作照片堆栈效果
- 转【实战体验几种MySQLCluster方案】
- linux性能监控工具
- php.ini 配置文件的深入解析
- linux学习笔记---未完待续,缓慢更新
- 使用python爬取MedSci上的期刊信息
- HDU 6055 Regular polygon
- Spark技术内幕:Shuffle Pluggable框架详解,你怎么开发自己的Shuffle Service?
- 【Netty源码分析】客户端connect服务端过程
- 【记录】垃圾清理软件 便携版CleanMyPC破解版
- 第一节:从面向对象思想(oo)开发、接口、抽象类以及二者比较
- POJ 1149 PIGS 【最大流】
- unicode utf-8 ascll编码比较
- 《Linux内核设计与实现》Chapter 2 读书笔记
- AngularJS双向绑定,手动实施观察