1
votes

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));
}
2
by counting at the beginning of the word instead of counting at the end of the word. stackoverflow.com/a/25752972/971127 Also, numberOfWords, numberOfLines must initialize to 0.BLUEPIXY
You don't need fgets() 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

2 Answers

0
votes
  1. fgets() stores the line ending character, so you can check that as well to mark an end of word
  2. Your code already reads multiple lines of input
0
votes

Why use fgets at all?

#include<ctype.h>
#include<stdio.h>

int main(void)
{
        int c;
        enum {in, out} state = out;
        int line_count = 0;
        int word_count = 0;
        while( ( c = fgetc(stdin)) != EOF ) {
                if(isspace(c)) {
                        state = out;
                } else {
                        if( state == out )
                                word_count += 1;
                        state = in;
                }
                if( c == '\n')
                        line_count += 1;
        }
        printf( "words: %d\n", word_count );
        printf( "lines: %d\n", line_count );
        return 0;
}