简体   繁体   中英

C - do while loop won't stop running

I'm trying to run a source code from "Programming Languages : Principles and Practice by Kenneth C. Louden" in xCode and for some reason the while loop only stops when the user input a number. For every other case, the while loops keeps running. Is there a reason why it's doing this?

typedef enum {TT_PLUS, TT_TIMES, TT_LPAREN, TT_RPAREN, TT_EOL, TT_NUMBER, TT_ERROR} TokenType;

int numVal; /*computed numeric value of a NUMBER token */
int currChar; /*current character*/

TokenType getToken(){
    while (currChar == ' '){ //Skips blanks
        currChar = getchar();
    }
    if (isdigit(currChar)){
        numVal = 0;
        while (isdigit(currChar)){//Compute numeric value
            numVal = 10 * numVal + currChar - '0';
            currChar = getchar();
        }
        return  TT_NUMBER;
    }
    else{ //recognize a special symbol
        switch (currChar){
            case '(': return TT_LPAREN; break;
            case ')': return TT_RPAREN; break;
            case '+': return TT_PLUS; break;
            case '*': return TT_TIMES; break;
            case '\n': return TT_EOL; break;
            default: return TT_ERROR; break;
        }

    }
}

int main() {
    //printf("Print tokens to scan:\n");
    TokenType token;
    currChar = getchar();

    do {
        token = getToken();
        switch(token){
            case TT_PLUS: printf("TT_PLUS\n"); break;
            case TT_TIMES: printf("TT_TIMES\n"); break;
            case TT_LPAREN: printf("TT_LPAREN\n");break;
            case TT_RPAREN: printf("TT_RPAREN\n");break;
            case TT_EOL: printf("TT_EOL\n"); break;
            case TT_NUMBER : printf("TT_NUMBER: %d\n",numVal);break;
            case TT_ERROR : printf("TT_ERROR: %c\n", currChar); break;
        }
    }while (token != TT_EOL);
    return 0;
}

Simply replacing your while loop at the begging of getToken with:

do {
    currChar = getchar();
} while (currChar == ' ');

Seems to do the trick for me ...

So the problem seems to be caused by your lexer getting stuck reading the same token over and over again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM