Thread: Text analysis problem

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    13

    Text analysis problem

    How could I write a program that reads a file of words (assumed to be in lower case letters) and prints out the total number of words in the file?

    Would it be something like this?:


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

    int main()
    {
    int ch;
    FILE *input_ptr;

    if((input_ptr=fopen(“infile.txt”,”rt”))==NULL)
    {
    printf(“Cannot open input file/n”);
    exit(1);
    }



    fclose(input_ptr);

    return 0;

    }

    I don't know how to do the bit in the middle.

    If anyone can help, thank you very much.

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    I will not code the solution for you but will give a hint - words are usually separated by a space. If you count the number of spaces then maybe add one more for the last word before the eof character, then that should take care of it.
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  3. #3
    Registered User
    Join Date
    Apr 2002
    Posts
    13
    ok, would it be something like this:

    while ((ch=fgetc(input_ptr))!=EOF))
    {
    if ((ch == 0x20) /*or should I write ==' ' ?*/
    ++count
    }

    printf("The number of words is %d\n", count-1);

  4. #4
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Code:
    int count = 0;
    
    while ((ch=fgetc(input_ptr))!=EOF)) 
    { 
    if ((ch == '  ' ) /*one space */
    count++;
    } 
    count++;
    
    printf("The number of words is %d\n", count);
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading Text File (spaces problem)
    By kekewong in forum C Programming
    Replies: 1
    Last Post: 04-15-2009, 03:34 PM
  2. Problem with text cursor in C
    By sureshkumarct in forum C Programming
    Replies: 3
    Last Post: 12-22-2006, 12:17 AM
  3. Problem drawing Rectangles and Text
    By cram in forum Windows Programming
    Replies: 2
    Last Post: 10-13-2004, 09:51 PM
  4. Problem parsing comments and such in text file
    By zaxxon in forum C Programming
    Replies: 3
    Last Post: 08-09-2004, 12:14 AM
  5. Text file manipulation problem
    By ferretman in forum C Programming
    Replies: 3
    Last Post: 12-20-2001, 02:40 AM