word count help?

This is a discussion on word count help? within the C Programming forums, part of the General Programming Boards category; Code: #include <string.h> #include <ctype.h> void main() { typedef char* string; char s[100]; int i,alpha=0,space=0; printf("Enter a sentence : "); ...

  1. #1
    Registered User n3cr0_l0rd's Avatar
    Join Date
    Feb 2009
    Posts
    62

    word count help?

    Code:
    #include <string.h>
    #include <ctype.h>
    
    void main()
    {
      typedef char* string;
      char s[100];
      int i,alpha=0,space=0;
      printf("Enter a sentence : ");
      gets(s);
      l=strlen(s);
      for (i=0;i<l;i++)
      {
        if( isalpha(s[i]) )
          alpha++;
        else if(isspace(s[i]) )
        	{
          	if(s[i+1]!=' ' && i!=l-1 )
          		space++;
          }
      }
      printf("\nAlphabets = %d",alpha);
      printf("\nWords     = %d",space+1);
      getch();
    }
    this will count the words properly even if there are several spaces in a row... if the sentence ends in spaces, then also this will work... but if the sentence starts with spaces, it wont work... any suggestions?
    Last edited by n3cr0_l0rd; 02-05-2009 at 10:55 PM.

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Make a variable to act as a toggle - or boolean - switch. It's either 1 (on), or 0, (off).

    Say it is called in_word. When you start off, in_word will be 0, because obviously, you're not inside a word yet. When you reach the first letter/digit, then in_word becomes 1, and thereafter, whenever in_word switches back to 0, because you have reached a non-letter/non-digit, then you add one to your word count.

  3. #3
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    use a flag
    inWord
    set it to 0 at the beginning
    on encountering alpha char - switch it to 1
    on encountering non-alpha - (or whitespace) switch it back
    count words when flag is changed from 0 to 1

    ===========
    Additional notes

    main should be
    int main(void) - read FAQ

    do not use gets - red FAQ


    typedef char* string; - do you use it?
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  4. #4
    C is Sea. I know a drop! ganesh bala's Avatar
    Join Date
    Jan 2009
    Location
    Bangalore
    Posts
    58

    Red face try this......

    Almost Same logic as vart and adak..

    Below code Will do...

    Take care of spaces and tabs....


    [ Someone can optimise this ........]


    Code:
     int in=1,words=0,wordin=0,flag=1;
    ...................................
    
    
    if( (s[i]=='  '|| s[i]=='\t') && isalpha(s[i+1]))
          {
            wordin=1;
            flag=0;
          }
              
        else if ( isalpha(s[i]) && (s[i+1]=='  ' || s[i+1]=='\0'|| s[i+1]=='\t'))
         {   
                  wordin=0;
                  flag=1;
                  goto count;
          }
         else
         {
           if(i==0 && s[i]!='  ')
            wordin=1;
            flag=0;
         }
                            
          count: if(wordin==0 && flag==1 )
                   words++;                  
                  
      }

  5. #5
    Registered User
    Join Date
    Feb 2009
    Posts
    138
    you can use scanf too. it's easier to get right than counting whitespace yourself.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int words = 0;
        printf("enter a sentence> ");
        while (scanf("%*s") != EOF) ++words;
        printf("there were %d words\n", words);
        return EXIT_SUCCESS;
    }

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Although meldreth's method does cound 123 as a word, as well as any other sequence of characters that aren't whitespaces.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,650
    Grr... I think n3cr0_l0rd did not specify the requirements properly. Guessing based on the code posted, I think that both the letter count and the word count should be printed.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User n3cr0_l0rd's Avatar
    Join Date
    Feb 2009
    Posts
    62
    hmm.. yes i was going to count letters as well as words...

  9. #9
    Registered User n3cr0_l0rd's Avatar
    Join Date
    Feb 2009
    Posts
    62
    Quote Originally Posted by vart
    Additional notes

    main should be
    int main(void) - read FAQ

    do not use gets - red FAQ


    typedef char* string; - do you use it?
    I didnt find anything like that in FAQ... can u plz help me?


    any yes, meldreths method doesnt print the result line until i press ctrl+c.... (i am using borland 5.02)
    Last edited by n3cr0_l0rd; 02-06-2009 at 06:51 PM.

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    The function main() should always return an integer. 0, by convention, means the program terminated normally. a return value of 1 means it was an abnormal termination.

    fgets() stops the possible overflow of a buffer. It only puts in as many char's as you tell it to allow.

    See your borland help page for more details - put your cursor on the word, and press ctrl + F1, I believe.

    If a line of print doesn't print, there are two ways to make it print: 1) add a newline at the end of the printed message, or 2) fflush(all). Both will flush the output buffer.

  11. #11
    Registered User n3cr0_l0rd's Avatar
    Join Date
    Feb 2009
    Posts
    62
    finally i did it..
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #include <conio.h>
    int main(void)
    {
      char s[100];
      int i,l,letters=0,words=0;
      printf("Enter a sentence : ");
      fgets(s,100,stdin);
      l=strlen(s);
      for (i=0;i<l;i++)
      {
        if (isalnum(s[i])) letters++;
        if (s[i]!=' ' && s[i+1]==' ') words++;   
      }
      if (s[i-2]==' ') words--;
      printf("\nTotal letters(alphabets and numbers) = %d",letters);
      printf("\nWords                                = %d",words+1);
      getch();
      return(0);
    }
    thx guys.... btw, is there other way to optimize this ?
    is there any other way to loop until the end of input string?
    Last edited by n3cr0_l0rd; 02-06-2009 at 08:36 PM.

  12. #12
    Registered User n3cr0_l0rd's Avatar
    Join Date
    Feb 2009
    Posts
    62
    s[i]!=' ' && s[i+1]==' ' indicates an increment to words... isnt the logic same as using inword concept?
    i tried with several sentences and it worked fine...
    btw, isalnum() checks if the argument is alpha-numeric or not.

  13. #13
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    Quote Originally Posted by n3cr0_l0rd View Post
    I didnt find anything like that in FAQ... can u plz help me?


    any yes, meldreths method doesnt print the result line until i press ctrl+c.... (i am using borland 5.02)
    FAQ > What's the difference between... > main() / void main() / int main() / int main(void) / int main(int argc, char *argv[])

    FAQ > Explanations of... > Why gets() is bad / Buffer Overflows
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  14. #14
    Registered User n3cr0_l0rd's Avatar
    Join Date
    Feb 2009
    Posts
    62
    oh.. now i will never use void main() and tomorrow, i am gonna quarrel with my teacher.. hehe

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, 08:12 AM
  5. Replies: 5
    Last Post: 09-28-2004, 12:38 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21