微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > 文字转声明: 编写程序将特定格式的输入转换为C语言声明

文字转声明: 编写程序将特定格式的输入转换为C语言声明

时间:11-22 来源:互联网 点击:
一. 程序功能

编写程序特定格式的输入转换为C语言声明.

二. 程序源码

#include

#include

#include

#define MAXTOKEN 100

enum {NAME, PARENS, BRACKETS};

int tokentype;

char token[MAXTOKEN];

char name[MAXTOKEN];

char datatype[MAXTOKEN];

char out[1000];

int p_getch(void);

void p_ungetch(int);

int main(void)

{

int type, lasttype;

char temp[MAXTOKEN];

printf("Please input(ctrl+z to quit)\n");

while (gettoken() != EOF)

{

strcpy(out, token);

lasttype = 0;

while ((type = gettoken()) != \n)

{

if (type == NAME)

{

sprintf(temp, "%s %s", token, out);

strcpy(out, temp);

}

else

{

if (lasttype == *)

{

sprintf(temp, "(%s)", out);

strcpy(out, temp);

}

if (type == PARENS || type == BRACKETS)

strcat(out, token);

else if (type == *)

{

sprintf(temp, "*%s", out);

strcpy(out, temp);

}

else

printf("Error: Invalid input at %s!\n", token);

}

lasttype = type;

}

printf("%s\n",out);

}

return 0;

}

int gettoken(void)

{

int c;

char *p = token;

while ((c = p_getch()) == || c == \t)

;

if (c == ()

{

if ((c = p_getch()) == ))

{

strcpy(token, "()");

return tokentype = PARENS;

}

else

{

p_ungetch(c);

return tokentype = (;

}

}

else if (c == [)

{

for (*p++ = c; (*p++ = p_getch()) != ];)

;

*p = \0;

return tokentype = BRACKETS;

}

else if (isalpha(c))

{

for (*p++ = c; isalnum(c = p_getch());)

*p++ = c;

*p = \0;

p_ungetch(c);

return tokentype = NAME;

}

else

return tokentype = c;

}

#define BUFSIZE 100

char buf[BUFSIZE];

int bufp = 0;

int p_getch(void)

{

return (bufp > 0) ? buf[--bufp]: getchar();

}

void p_ungetch(int c)

{

if (bufp < BUFSIZE)

buf[bufp++] = c;

else

printf("Error: (ungetch) Too many chars in buffer1\n");

}

三. 程序小结

比如:

输入: x * char

输出: char *x

输入: daytab * [13] int

输出: int (*daytab)[13]

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top