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:
I don't understand why but apparently the loop ends prematurely after the first space the program encounters.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;
}
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?