Click here to Skip to main content
15,902,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I just put some c code into MS c++ 6.0 to run, but the code is not work.
It can't output the expectation result. anyone can help? thanks:-


C++
#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);
}


[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 7-Dec-11 3:10am
v3
Comments
Albert Holguin 7-Dec-11 9:12am    
What do you mean it doesn't work? Be more specific, does it not do what you expect? Does it crash? Does it not compile? Does it not link?
Legor 7-Dec-11 9:12am    
What exactly isn't working?

It's because you're looking for ' 0 ' instead of '0'. In other words, remove the padding for everything except the space character.
 
Share this answer
 
The first thing to note is that you need to get rid of the spurious spaces in your comparison literals.
at the moment, the comparison is against teh whole value "space zero space" rather than "zero".
Try:
C++
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);
c = getchar();
Note that I have included block start and end around every statement, even when they aren't necessary. It is worth doing this, particularly when you are just starting, as you can easily be confused by indentation into thinking a loop goes further than it actually does:
C++
while (c != EOF)
   printf(".");
   c = getchar();
Looks like it works, but
C++
while (c != EOF)
{
   printf(".");
   c = getchar();
}
Actually does!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900