本文主要是介绍C //练习 5-19 修改undcl程序,使它在把文字描述转换为声明的过程中不会生成多余的圆括号。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C程序设计语言 (第二版) 练习 5-19
练习 5-19 修改undcl程序,使它在把文字描述转换为声明的过程中不会生成多余的圆括号。
注意:代码在win32控制台运行,在不同的IDE环境下,有部分可能需要变更。
IDE工具:Visual Studio 2010
代码块:
#include <ctype.h>
#include <stdio.h>
#include <string.h>#define MAXTOKEN 100
#define MAXPOINTERS 10enum { NAME, PARENS, BRACKETS };int gettoken(void);
int tokentype;
char token[MAXTOKEN];
char out[1000]; int getch(void);
void ungetch(int);int main() {int type;int i, c, pcount;char temp[MAXTOKEN];char p[MAXPOINTERS];while (gettoken() != EOF) {strcpy(out, token);while((type = gettoken()) != '\n')if (type == PARENS || type == BRACKETS)strcat(out, token);else if (type == '*') {pcount++;while ((c = getch()) == '*' || c == ' '){if (c == '*'){if (pcount < (MAXPOINTERS - 1))pcount++;elsebreak;}}ungetch(c);for (i = 0; i < pcount; i++){p[i] = '*';}p[i] = '\0';pcount = 0;sprintf(temp, "(%s%s)", p, out);strcpy(out, temp);} else if (type == NAME) {sprintf(temp, "%s %s", token, out);strcpy(out, temp);} elseprintf("invalid input at %s\n", token);printf("%s\n", out);}return 0;
}int gettoken(void) {int c;char *p = token;while ((c = getch()) == ' ' || c == '\t');if (c == '(') {if ((c = getch()) == ')') {strcpy(token, "()");return tokentype = PARENS;} else {ungetch(c);return tokentype = '(';}} else if (c == '[') {for (*p++ = c; (*p++ = getch()) != ']'; );*p = '\0';return tokentype = BRACKETS;} else if (isalpha(c)) {for (*p++ = c; isalnum(c = getch()); )*p++ = c;*p = '\0';ungetch(c);return tokentype = NAME;}return tokentype = c;
}#define BUFSIZE 100char buf[BUFSIZE];
int bufp = 0; int getch(void) {return (bufp > 0) ? buf[--bufp] : getchar();
}void ungetch(int c) {if (bufp >= BUFSIZE)printf("ungetch: too many characters\n");elsebuf[bufp++] = c;
}
这篇关于C //练习 5-19 修改undcl程序,使它在把文字描述转换为声明的过程中不会生成多余的圆括号。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!