Thread: Average word length

  1. #1
    Registered User
    Join Date
    Nov 2019
    Posts
    4

    Post Average word length

    Hi, I'm fairly new. I just started a few weeks ago my C programming course in university (I'm a mechanical engineering student).
    I wanted to create a program that calculates the average length of words in a sentence.
    I tried this:

    Code:
    #include<stdio.h>
    
    int length = 0, words = 1;
    
    int main()
    {
       printf("Enter sentence: ");
       
       while(getchar() != '\n')
       {
        length++;
         if(getchar() == ' ')
          words++;
        }
        printf("The average length of a word is: %d", length / words);
    
    return 0;
    }
    I don't understand why but apparently the loop ends prematurely after the first space the program encounters.
    For example I gave "Ciao Mondo" as an input and the values of length and words were respectively 5 and 1.
    Any idea what might cause this?

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    You have several problems here.

    When your first getchar() gets a space, the second gets the next char after the space, turning the whole line into one big word!

    Look at the following with my changes and notes:
    Code:
    #include <stdio.h>
    
    int main()
    {
       // Make all your variables local, NOT global!
       int length = 0, words = 0; // No words have been entered
       int ch = 0; // To capture the value returned from getchar()
    
       printf("Enter sentence: ");
    
       while((ch = getchar()) != '\n')
       {
          length++;
    //     if(getchar() == ' ') // This would get the next char in the buffer
          if(ch == ' ') // Check the value captured in the getchar() above
             words++;
       }
       printf("The average length of a word is: %d\n", length / words);
    
       return 0;
    }

  3. #3
    Registered User
    Join Date
    Nov 2019
    Posts
    4
    Oh I see! I thought the program would consider the same char for the whole duration of the loop!
    Thank you so much! As soon as I can I’m going to modify my program!

  4. #4
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    I do see why you initialize words to 1; I would have written this a little differently.

  5. #5
    Registered User
    Join Date
    Nov 2019
    Posts
    4
    I’d be curious to see how you would have written this! Could you show me?

  6. #6
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    Quote Originally Posted by PondaKonatsu View Post
    I’d be curious to see how you would have written this! Could you show me?
    Following the style of your code, this might be my version:
    Code:
    #include <stdio.h>
    #include <ctype.h>  // For isspace()
    
    /**
     ** This version still has it's problems.
     **   Empty line, just the newline
     **   Multiple whitespace chars between the words
     **   Leading and trailing whitespace chars
     **/
    
    int main(void)
    {
       // Make all your variables local, NOT global!
       int length = 0, words = 0; // No words have nbeen entered
       int ch = 0; // To capture the value returned from getchar()
    
       printf("Enter sentence: ");
    
       while(1)  // Infinite loop until break;
       {
          ch = getchar();
    
          if(ch == '\n')
          {
             words++; // End of line, count last word
             break;
          }
    
          // Else check for end of word, checking for any whitespace char, other than a newline
          // Think tab, vertical tab, formfeed, etc...
          if(isspace(ch)) // Check the value captured in the getchar() above
          {
             words++;
          }
          else
          {
             length++; // Only count letters in the word, not any spaces
          }
       }
       printf("Total length of the letters in words: %d, Number of words: %d\n", length, words);
    
       // Choose one of the following:
       printf("The average length of a word is: %d\n", length / words); // Integer division
       printf("The average length of a word is: %f\n", (float) length / words); // Floating point division
    
       return 0;
    }
    A more advanced version that I would normally use, would be to input the entire line using fgets(), then parse the line using strtok(). You may not have studied these functions yet. There are other solutions as well, such as using scanf().
    Last edited by rstanley; 11-21-2019 at 11:27 AM.

  7. #7
    Registered User
    Join Date
    Nov 2019
    Posts
    4
    Unfortunately I haven't seen yet the functions you mentioned. I just studied the loops and the different types of formats for inputs. Still, I could understand the last code you sent me! Thank you very much for your guidance and patience! Have a nice day!

  8. #8
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Another one for your study:
    Code:
    /* Compile with GCC:
    
      gcc -o test test.c
    
      Add -DDEBUG with you want to see 'debug' messages. */
    #define _GNU_SOURCE
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    
    #define SEPARATORS " \t,.;:?!<>[]{}#$%*()_+="
    
    int main( int argc, char *argv[] )
    {
      char *p;
      size_t words, size;
    
    #ifdef DEBUG
      size_t n = 0;
    #endif
    
      if ( argc != 2 )
      {
        fprintf( stderr, "Usage: %s <string>\n", basename( *argv ) );
        return EXIT_FAILURE;
      }
    
      words = size = 0;
    
      p = strtok( *++argv, SEPARATORS );
    
      while ( p )
      {
        size_t len;
    
        words++;
    
        if ( len = strlen( p ) )
          size += len;
    
    #ifdef DEBUG
        printf( "%zu: \"%s\" (size=%zu, words=%zu)\n", ++n, p, size, words );
    #endif
    
        p = strtok( NULL, SEPARATORS );
      }
    
      printf( "%zu words found.\n"
              "Average words length: %.3f characters.\n", words, ( double )size / words );
    
      return EXIT_SUCCESS;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Write a histogram of word length (K&R 1.13 assignment)
    By Dino Sylence in forum C Programming
    Replies: 1
    Last Post: 04-16-2015, 02:10 AM
  2. Word Length Statistics
    By tobig in forum C Programming
    Replies: 2
    Last Post: 10-25-2014, 12:20 PM
  3. changing word length
    By mltngpot in forum C++ Programming
    Replies: 7
    Last Post: 01-21-2006, 09:55 AM
  4. Replies: 5
    Last Post: 09-28-2004, 12:38 PM
  5. average function length...
    By endo in forum C++ Programming
    Replies: 6
    Last Post: 08-16-2002, 04:12 PM

Tags for this Thread