MNY
MNY

Reputation: 1536

I'm getting the wrong output from a program example in k & r chapter 1.6

i know there is another question on the same example, but for different issue.

This is the code example:

#include <stdio.h>
/* count digits, white space, others */
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);
}

After I run is and execute the program with Ctrl + D, I get: digits = 0 0 0 0 0 0 0 0 0 0, white space = 0, other = 0. From Xcode...

But in the book they say "The output of this program on itself is: digits = 9 3 0 0 0 0 0 0 0 1, white space = 123, other = 345"

Can you tell me whats going on please..tnx.

Upvotes: 2

Views: 226

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180987

From the book;

The output of this program on itself is
digits = 9 3 0 0 0 0 0 0 0 1, white space = 123, other = 345

Trying it with its own source as input;

> gcc test.c
> ./a.out < test.c

digits = 9 3 0 0 0 0 0 0 0 1, white space = 125, other = 345

Close, but I suspect the cut'n'paste from StackOverflow may account for the 2 extra white spaces :)

Upvotes: 1

Related Questions