Design a word and character counter and display a histogram of particular characters.

The histogram may use any character to denote a single instance of a particular letter, such as an X, and should print the number of instances for that letter at the end of the line. Only print the results for characters that have one or more occurrences in the entered sentence. Your program must treat lower case and upper case of the same letter as separate characters.

Below is an example of what a histogram might look like for the sentence: i Looooove eps II

Word total: 4
Character total: 18

e: XX (2)
i: X (1)
o: XXXXX (5)
p: X (1)
s: X (1)
v: X (1)
I: XX (2)
L: X (1)

My problem is that when I compile and test the program, only a histogram for the first word of the sentence is printed to the screen, I dont know if entering a space is stopping the rest of the program from completing? Here is the code I have for the histogram function.

void histogram(char array3[]){
    int counts[256] = {0};

    int num_words = 0;         
    int num_chars = 0;         
    int num_underscores = 0;   
    int in_word = 0;           
    int i,x,j;

    for( i = 0; array3[i] != 0; i++ ){
        if( isalpha(array3[i]) ){

    for(i = 0; i < 256; i++ ){
        if( counts[i] == 0 ) continue;
            printf( "%c: ", (char)i );

        for(x = 0; x < counts[i]; x++ ) fputc('X', stdout);
            printf("(%d)\n", counts[i] );

Edited by sbouxsein

3 Years
Discussion Span
Last Post by sbouxsein

I could be wrong, but the code you've posted looks OK. I'd guess that the problem is more likely to be in your code which deals with getting input from the user. I suspect that you may only be getting everything up to the first whitespace character in the input stream rather than the entire line entered by the user.

To verify this, try running your program through a debugger:
- Set a breakpoint at the start of your histogram function and run the program.
- Enter a sentence including some space characters
- When the breakpoint is hit, ensure that the string passed into the function matches what you entered.

If the input string matches what you entered, then I've probably missed something silly in your posted code and I'm therefore a complete idiot! But if it doesn't match up, (I suspect it will only contain the first word) you can be 100% sure it's the way that you are getting input from the user that is causing the problem!

Personally, I think it's the code which gets input from the user that is the problem, not your histogram function!

Edited by JasonHippy


Yep, that's absolutely right. Another function in my main program was changing the character array before it gets passed to this function. Thank you for your help!

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.