Thread: Word Count gone kookoo :)

  1. #1
    Registered User Spectrum48k's Avatar
    Join Date
    May 2002
    Posts
    66

    Word Count gone kookoo :)

    after manipulating an existing program from a book to get a word count, i get a proper count only if i type a space as a first entry. if i start typing immediately after running this program i get 1 less word in my count. .. and now for the unexpected question........................why ?

    #include <stdio.h>

    #define IN 1 /* inside a word */
    #define OUT 0 /* ouside a word */

    main()
    {
    int c, other, word, state;
    other = word = 0;
    while((c = getchar()) != EOF) {
    ;
    if (c == ' ' || c == '\n' || c == '\t')
    state = OUT;
    if (state != OUT)
    ++word;
    }
    printf("%d \n", word);
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    See if you can find the changes I made and why. (Hints: else if, initializing and testing state)
    Code:
    #include <stdio.h>
    
    #define IN 1 /* inside a word */
    #define OUT 0 /* ouside a word */
    
    int main ( void )
    {
      int c, word = 0, state = OUT;
      while((c = getchar()) != EOF) {
        if (c == ' ' || c == '\n' || c == '\t')
          state = OUT;
        else if (state == OUT) {
          state = IN;
          ++word;
        }
      }
      printf("%d\n", word);
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User Spectrum48k's Avatar
    Join Date
    May 2002
    Posts
    66
    the "other" was useless because all spaces, \n's etc get asigned to the "OUT" state .

    also you set the state to OUT at the start of program while initializing it.

    and yes.. ELSE IF

    thanx..

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bintree and count (withouth using template)?
    By cubimongoloid in forum C++ Programming
    Replies: 7
    Last Post: 05-24-2009, 06:22 AM
  2. word count
    By unity_1985 in forum C Programming
    Replies: 3
    Last Post: 07-29-2007, 10:34 AM
  3. Replies: 7
    Last Post: 06-16-2006, 09:23 PM
  4. word count troubles
    By Hoser83 in forum C Programming
    Replies: 13
    Last Post: 02-09-2006, 09:12 AM
  5. Replies: 5
    Last Post: 09-28-2004, 12:38 PM