I am new to C and I am having trouble with this program. I'm trying to read text from stdin until EOF and write to standard output the number of words read and the number of lines of input. A word being defined as any string of characters except whitespace. My problems are (1) when the program has to read the last word in a line, it reads an end of line and not a whitespace so it does not add the word, and (2) when the program has to read multiple lines of input. Do I need to do a nested for loop with fgets to read until != "\n"? I am not sure on that one. Here is what I have right now:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char previousLetter;
char line[500];
int numberOfWords, numberOfLines, length, i;
while (fgets (line, 500, stdin) != NULL)
{
length = strlen(line);
if (length > 0)
{
previousLetter = line[0];
}
for (i=0; i <= length; i++)
{
if(line[i] == ' ' && previousLetter != ' ')
{
numberOfWords++;
}
previousLetter = line[i];
}
numberOfLines++;
}
printf ("\n");
printf ("%d", numberOfWords);
printf (" %d", (numberOfWords / numberOfLines));
}
numberOfWords, numberOfLines
must initialize to 0. – BLUEPIXYfgets()
for this. All you really care about is (a) is it whitespace?, and if so (b) is it a newline. Consecutive whitespace should be accounted for as well, so as not to pad the word-count incorrectly. – WhozCraig