Originally Posted by
PondaKonatsu
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().