C程序逐字符读取数字,给出错误的结果

Swa*_*wri 1 c

#include<stdio.h>
#include<ctype.h>

int peekchar() {
    int c;
    c = getchar();
    if (c != EOF) {
        ungetc(c, stdin);
    }   
    return c;
}

int readNumber(void) {
    int c;
    int accumulator = 0;
    while ((c = peekchar() != EOF) && isdigit(c)) {
       c = getchar();
       accumulator *= 10; 
       accumulator += c - '0';
    }   
    return accumulator;
}

int main() {
    int result = readNumber();
    printf("%d\n", result);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我试图从stdin读取以十进制表示法写入的整数,直到第一个非数字.但它没有给出正确的结果:

M1508444:CProg sb054043$ gcc -g3 readNumber.c -o readNumber
M1508444:CProg sb054043$ ./readNumber 
123
0
Run Code Online (Sandbox Code Playgroud)

有人可以帮我识别问题吗?

Bat*_*eba 5

问题在于运算符优先级.c = peekchar() != EOF被分组为c = (peekchar() != EOF),或者c是,0或者1,它们都是结果.

修复(c = peekchar()) != EOF.

或者,如果将isdigit其定义为0 EOF,则可以将循环条件简化为

while (isdigit(c = peekchar())){
Run Code Online (Sandbox Code Playgroud)