"The C Programming Language", 2nd edition, Kernighan and Ritchie

Answer to Exercise 4-11, page 83

Solution by Gregory Pietsch

Modify getop so that it doesn't need to use ungetch. Hint: use an internal static variable.

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




Back to index





You are visitor number - call again soon!