Thread: error while counting the number of words entered by user

  1. #1
    Registered User
    Join Date
    Feb 2012
    Location
    Trinidad & Tobago
    Posts
    43

    error while counting the number of words entered by user

    The program is intended to count the number of characters, words and lines entered. the program runs fine if only one line of text is entered, but if more that one line of text is entered the "number of words" that the program outputs is incorrect: here's my code
    Code:
    #include <stdio.h>
    
    
    int main(void){
           int c;
           int cha=0;  // character counter
           int wd=0;   // word counter
           int nl=0;   // newline counter
           int flag=0;
        
           while( (c=getchar() )!= EOF){
                
                if(c=='\n'){
                      nl++;
                }
                if (c!='\n'){
                      cha++;
                      if(c==' '){
                          flag=0 ;        
                      }                         
                      else if(flag==0){
                           wd++;
                           flag=1;     
                      }                      
                } 
           }
           printf("The string entered is %d lines,",nl);
           printf("contains %d words,",wd);  
           printf("and is %ld characters long",cha);
           getchar();
           return 0;
    }
    please help me it's frustrating

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Well for one thing the program assumes that a word is separated by a space character. The first word of the next line was actually preceded by '\n', so you would have to work out where to add it to the count.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Counting the number of words input
    By lostnthestars in forum C++ Programming
    Replies: 2
    Last Post: 12-19-2011, 04:32 AM
  2. random number within user entered range
    By me77 in forum C++ Programming
    Replies: 5
    Last Post: 03-10-2010, 08:11 PM
  3. Replies: 7
    Last Post: 04-12-2009, 12:40 PM
  4. counting the number of words
    By ccoder01 in forum C Programming
    Replies: 3
    Last Post: 05-29-2004, 02:38 AM
  5. counting the number of words in a file
    By stuartbut in forum C Programming
    Replies: 2
    Last Post: 04-13-2002, 08:19 AM