Thread: problem in histogram word

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    187

    problem in histogram word

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #define SIZE 100
    int main(void)
    {
        char *name;
        int i,c,x;
        int histogram[10];
        name=malloc(sizeof (char) * SIZE);
        x=0;
        for(i=0;i<10;i++)
            histogram[i]=0;
        for(;;){
            fgets(name,SIZE,stdin);
            x=strlen(name);
            puts(name);
            /*next our test in histogram*/
            if (x >= '0' && x <= '9')
                  ++histogram[x-'0'];
            /*next step showing it*/
            puts("its histogram is\n");
            for(i=0;i<10;i++){
                printf("%d ",histogram[i]);}
            puts("\n");
            /*intilising all back to 0 and freeing back*/
            x=0;
            for(i=0;i<10;i++)
                histogram[i]=0;
            free(name);
            name=malloc(sizeof (char) * SIZE);
            continue;}
        return 0;
    }
    it alawys shows the histogram alawys 0 i dunno why;

  2. #2
    Making mistakes
    Join Date
    Dec 2008
    Posts
    476
    I don't really understand what you want, but i think the wrong piece is the line

    Code:
    x = strlen(name)
    That means, x is the length of the input. Then you're checking if x represents a digit. propably no. What you wanted is:

    Code:
    x = name[0]
    Some advice, not really related:
    * You could even say

    Code:
    x = getchar();
    and drop out name, SIZE, fputs, fgets and stdlib.
    * Why do you free/malloc all time? You don't need to.
    * You don't need your continue statement. It automatically jumps back to the beginning of the loop.
    * You never use 'c', drop it out.
    * memset is really handy. Use it instead of a for loop setting every item manually to zero.
    Last edited by Brafil; 04-18-2009 at 09:59 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  2. New problem [Beginner]
    By Vintik in forum C++ Programming
    Replies: 2
    Last Post: 08-18-2005, 11:33 PM
  3. Passing structures to a function
    By earth_angel in forum C++ Programming
    Replies: 5
    Last Post: 07-13-2005, 06:13 AM
  4. Find a word in a 2d grid
    By The_Kingpin in forum C++ Programming
    Replies: 2
    Last Post: 02-24-2005, 05:38 PM
  5. Wrong Output
    By egomaster69 in forum C Programming
    Replies: 7
    Last Post: 01-28-2005, 06:44 PM