Thread: what's wrong with my counting digits code?

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    33

    what's wrong with my counting digits code?

    Good day
    I'm trying to write a counting digits code

    Code:
    int main()
    {
        int numdigit[10], c,i;
        c=getchar(); i=0;
    
    
        for(i=0;i<10;++i)
            numdigit[i]=0;
        while((c=getchar())!=EOF & c>='0' & c<='9')
           ++numdigit[c-'0'];
        printf("the digits are");
        for(i=0;i<10;++i)
            printf("%d",numdigit[i]);
    
    
    }
    the problem is that when i entred 123 I got 0011000000 !
    any help would be highly appreciated!

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    You have a premature "getchar()" on line 4.

    Note the difference between bitwise & and logical &&.

  3. #3
    Registered User
    Join Date
    Nov 2016
    Posts
    33

    RE

    Quote Originally Posted by Matticus View Post
    You have a premature "getchar()" on line 4.

    Note the difference between bitwise & and logical &&.
    Thank you it works fine now

    but i really would like to know why that premature c=getchar() affected my code that way?

    Thank you!!!

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Quote Originally Posted by amaelle View Post
    but i really would like to know why that premature c=getchar() affected my code that way?
    The input from the first "getchar()" (line 4) is not processed, as it is lost when the "getchar()" on line 9 is executed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trouble counting digits
    By never_lose in forum C Programming
    Replies: 13
    Last Post: 04-27-2011, 10:48 PM
  2. counting # of digits
    By tidbit in forum C++ Programming
    Replies: 4
    Last Post: 03-25-2010, 02:04 PM
  3. Counting quantity of different digits
    By cowa in forum C Programming
    Replies: 1
    Last Post: 11-17-2009, 12:09 PM
  4. Counting number of digits?
    By scatterice in forum C Programming
    Replies: 7
    Last Post: 05-12-2009, 01:30 PM
  5. Counting integer digits
    By Lionmane in forum C Programming
    Replies: 22
    Last Post: 05-24-2005, 10:11 AM

Tags for this Thread