Modify getop so that it doesn't need to use ungetch. Hint: use an internal static variable.
Solution by Gregory Pietsch, and Liangming
#include <stdio.h>
#define NUMBER '0'
int getop(char *s)
{
int c;
static int buf = EOF;
if (buf != EOF && buf != ' ' && buf != '\t'
&& !isdigit(buf) && buf != '.') {
c = buf;
buf = EOF;
return c;
}
if (buf == EOF || buf == ' ' || buf == '\t')
while ((*s = c = getch()) == ' ' || c == '\t')
;
else
*s = c = buf;
buf = EOF;
*(s + 1) = '\0';
if (!isdigit(c) && c != '.')
return c; /* not a number */
if (isdigit(c)) /* collect integer part */
while (isdigit(*++s = c = getch()))
;
if (c == '.') /* collect fraction part */
while (isdigit(*++s = c = getch()))
;
*++s = '\0';
buf = c;
return NUMBER;
}
Liangming's
int getop(char s[])
{
int i, c;
static char buf = EOF;
if (buf == EOF || buf == ' ' || buf == '\t') {
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
} else
c = buf;
if (!isdigit(c) && c != '.')
return c; /* not a number */
i = 0;
if (isdigit(c)) /* collect integer part */
while (isdigit(s[++i] = c = getch()))
;
if (c == '.') /* collect fraction part */
while (isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
buf = c;
return NUMBER;
}
'The C Programming Language' 카테고리의 다른 글
Chapter 4 - Functions and Program Structure 13 (0) | 2009.03.27 |
---|---|
Chapter 4 - Functions and Program Structure 12 (0) | 2009.03.27 |
Chapter 4 - Functions and Program Structure 10 (0) | 2009.03.27 |
Chapter 4 - Functions and Program Structure 9 (0) | 2009.03.27 |
Chapter 4 - Functions and Program Structure 8 (0) | 2009.03.27 |