Counting words in an string

This is a discussion on Counting words in an string within the C Programming forums, part of the General Programming Boards category; My program has to count the amount of times the word given as an argument to main is given by ...

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    16

    Counting words in an string

    My program has to count the amount of times the word given as an argument to main is given by the user. This all worked untill I added the bit where the program has to exit when EOF is the input.

    Here is my file

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void swap(int *p, int *q);
    
    int main(int argc, char *argv[])
    {
        char buf[1026] = {0};
        char *p = buf;
        int cnt = 0, i;
        const char *word = argv[1];
        int length_arg = strlen(argv[1]);
    
        while (fgets (buf, 1025, stdin) != "EOF")
        {
            for(i = 0; fgets (buf, 1025, stdin) != NULL; i++)
            {
                for (i = 0; i < 1025; i++)
                {
                    if (strncmp(p + i, word, length_arg) == 0)
                        cnt++;
                }
            }
            printf("%d", cnt);
        }
    
        printf("%d", cnt);
    
        return 0;
    }
    the input is:
    Let it be, let it be, let it be, let it be.
    Whisper words of wisdom, let it be.
    EOF

    The outcome should be (my argument to main is "let")
    4

    Can someone help me out?

  2. #2
    Registered User
    Join Date
    Apr 2011
    Posts
    16
    No worries, I got it

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    2,753
    In the following snippet:
    Code:
    while (fgets (buf, 1025, stdin) != "EOF")
    The fgets() either returns your buf, or NULL if it failed. However you can not use the operator!= with C-Strings, you must use strcmp() to compare C-Strings.

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 06-05-2010, 03:04 AM
  2. Counting the words in a string C++
    By mblue in forum C++ Programming
    Replies: 8
    Last Post: 03-30-2009, 01:39 PM
  3. Counting Characters And Words
    By SNaRe in forum C Programming
    Replies: 6
    Last Post: 05-04-2005, 10:48 AM
  4. help with counting words
    By geo_c in forum C Programming
    Replies: 7
    Last Post: 08-23-2004, 06:53 AM
  5. counting words in string
    By Unregistered in forum C Programming
    Replies: 9
    Last Post: 05-30-2002, 04:10 AM

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