Question

I just solved the exercise 4-10 - I replaced (unget/get)char with getline, but I can't add support for negative numbers. The reasoning is simple, if a char is a '-' and the character next to it is a digit or a decimal point we have a negative number. I don't know what I did wrong, first time i tryed something like this:

if(c != '-' && isdigit(line[lp])) {
    return c;
}

If we have a negative number, line 2 shouldn't be executed, and the array s will have as the first element a '-'. However, I get an infinite loop and i can't find the problem.

This is the most relevant piece of code for this problem(especially the 4th if statement in getop).

#define MAXLINE 100
char line[MAXLINE];
int lp = 0;
int lineLength  = 0;
int getline(char s[], int lim) {
    int i, c;
    i = 0;
    while(--lim > 0 && (c = getchar()) != EOF && c != '\n')
        s[i++] = c;
    if(c == '\n')
        s[i++] = c;
    s[i] = '\0';
    return i;
}
int getop(char s[]) {
    if(lp  == lineLength) {
        lineLength = getline(line, MAXLINE);
        lp = 0;
    }
    if(lineLength == 0)
        return EOF;
    char c;
    int i;
    printf("the execution is here\n");
    while((s[0] = c = line[lp++]) == ' ' || c == '\t')
        /* skip tabs an white spaces */;
    s[1] = '\0';
    if(!isdigit(c) && c != '.' && c != '-')
        return c;
    if(c == '-') {
        if(isdigit(line[lp]) || line[lp] == '.')
            /* nothing */;
       else
            return c;
    }
    i = 0;
    if(isdigit(c))
        while(isdigit((s[++i] = c = line[lp++])))
            ;
    if(c == '.')
        while(isdigit((s[++i] = c = line[lp++])))
            ;
    lp--;
    return NUMBER;
}
Was it helpful?

Solution

You need to advance lp when you find a '-'. The if's at the bottom of the function don't look for '-'. You'll notice other digits (and the decimal point) advances lp before the function returns, so you need to copy that '-' sign to s[] (or store it in global flag) and increment lp, otherwise it just processes the same character over and over.

Stepping through the code in a debugger would help you see the problem as well, if you look at what lp does for positive numbers vs. negative numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top