The C Programming Language

Chapter 4 - Functions and Program Structure 11

mmresult 2009. 3. 27. 13:57


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;
}