为什么 printf 只执行第一次?

问题描述 投票:0回答:1

这是代码:

#include <stdio.h>

main()
{
    int c, i, nwhite, nother;
    int ndigit[10];
    
    nwhite = nother = 0;
    
    for(i = 0; i < 10; ++i){
        ndigit[i] = 0;
    }
    
    while((c = getchar()) != EOF){
        if(c >= '0' && c <= '9'){
            ++ndigit[c-'0'];
        }else if(c == ' ' || c == '\n' || c == '\t'){
            ++nwhite;
        }else{
            ++nother;
        }
    }
    
    printf("Digits =");
    
    for(i = 0; i < 10; ++i){
        printf(" %d,", ndigit[i]);
    }
    
    printf("\nWhites = %d\nOthers = %d", nwhite, nother);
    
}

编译没有问题,但是当我运行它并输入随机数时,我得到以下结果:

1234556677

Digits =

它只运行第一个 printf,不显示其余部分。我尝试注释掉整个 while 循环,然后所有 printf 都显示出来,所以我认为 getchar() 一定存在一些问题,但我无法弄清楚。

我直接从 Windows 控制台使用 Mingw 编译器,无需 IDE。

我希望它打印所有的计数示例:

1234556677

Digits = 0, 1, 1, 1, 1, 2, 2, 2, 0, 0,
Whites = 0
Others = 0
c windows printf mingw getchar
1个回答
0
投票

您实际上并没有在 while 循环中使用此行加载 ndigit 数组: ++ndigit[c-'0'];请尝试这样的事情:

i = 0;  /* added */

while((c = getchar()) != EOF){
    if(c >= '0' && c <= '9'){
        ndigit[i++]c-'0';     /* updated */
    }else if(c == ' ' || c == '\n' || c == '\t'){
        ++nwhite;
    }else{
        ++nother;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.