Click here to Skip to main content
14,739,836 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to write a program which lets the user input a sentence and then calculates the average word length.

I want to count words by checking for space characters with an if sentence, however I do not understand why the condition in the if sentence is being passed as true in every loop.

The wordcount is always being printed as allchars + 1.

What I have tried:

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main(){
    
    char string[10000];
    int i, allchars;
    double wordcount = 0, charcount = 0;
    
    printf("Enter a sentence, whose ending will be marked by hitting enter.\n");
    fgets(string, 10000, stdin);
    
    allchars = strlen(string);
    
    printf("allchars = %d\n", allchars);
    
    for(i=0; i<allchars; i++){
        if(string[i] = ' ')
            wordcount += 1;
        else
            charcount += 1;
    }
    printf("number of words = %lf\n", wordcount);
    printf("number of chars = %lf\n", charcount);
    
    printf("average length of words is %lf", charcount/wordcount);
    
    return 0;
}
Posted
Updated 23-Nov-20 11:16am
v2
Comments
Rick York 23-Nov-20 16:12pm
   
Your for loop conditional statement should be i < allchars. If fgets includes the new line character you might want to eliminate it.

Let me give you an interesting strategy - since you want the average length of the words.

You need
(1) the length of the input string (sentence). C has a function for that
(2) the count of spaces in the string. Make sure you get rid of double spaces, etc.
(3) do you need to handle punctuation? You then need to remove (or not) punctuation from your string and decide how you'll handle hyphens.

The first two items, after considering the third, allow you to answer all of your questions. If you need modal and median word length then you have to actually look at the words, themselves - that's more work.

These two bits of information give you all you need for an average word length
   
This
if(string[i] = ' ')
doesn't do what you think it does. With a single equals sign (assignment operator) you're saying you want the character at index i to be ' ' (0x20). What you want is the comparison operator '==', is the character at index i equal to ' '.
if(string[i] == ' ')
   

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