digit count

digit count
0~9, 공백, 그외 문자 총 12개의 digit를 세는 프로그램

#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(", white space = %d, other = %d\n",
            nwhite, nother);
}

EOF까지 입력을 받으면서 해당 문자의 범위를 비교해서 카운트 하는 것이다.
배열을 선언하고 사용하는부분이 중요한것 같다.

새로운 것은 ++ndigit[c-'0']; 부분인데 c-'0'를 함으로써 문자를 숫자로 변환시켰다.


저작자 표시 비영리 변경 금지
Tag //
|  1  | ...  96  |  97  |  98  |  99  |  100  |  101  |  102  |  103  |  104  | ...  108  |