简体   繁体   English

C-做while循环不会停止运行

[英]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. 我试图在xCode中运行“编程语言:Kenneth C. Louden的原理和实践”中的源代码,由于某些原因,while循环仅在用户输入数字时停止。 For every other case, the while loops keeps running. 对于其他所有情况,while循环都会继续运行。 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: 只需将getToken请求的while循环替换为:

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. 因此,问题似乎是由您的词法分析器卡住反复读取同一令牌引起的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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