Basically I'm writing a program that reads in the number of words in a file and counts them based on the number of whitespaces, though I'm also considering using tokenising im just more familiar with whitespaces.

It compares the ACII code of whitespace(I think) then adds one due to not being able to read past the EOF marker. I havent quite got the code there yet though and I'm stumped, so any help is appreciated.

#include <stdio.h>

int main()
{
    FILE * fptr;
   if((fptr = fopen("words.txt", "r")) == NULL)
   {
      printf("Cannot open the file: input.txt\n");
   }
   else
   {
      printf("File opened successfully for reading\n");
   }
   
   int i;
   int word_number = 0;
   int total_words = 0;
   char myChar;
   char string[60];
   fptr = fopen("words.txt", "r");

   while(fgets(string, 60, fptr))
   {
       for(i=0; i>0; i++)
       {
          if(myChar == 0127)
          {
             word_number++;
          }
          
          total_words = word_number+1;
       }
   }
    
   printf("The number of words is: %d \n", total_words);
     
   fclose(fptr);
}

As I recall, the ASCII for a space is 32, not 0127 (which is a 'W'). I recommend you look at the isspace(int) function available from <ctype.h> as it will match all whitespace characters (spaces, newlines, tabs, etc...)

Although I don't agree with the method you're using to count the number of words, there are a number of errors in your code.

for(i=0; i>0; i++) // infinite loop
   {
      if(myChar == 0127) // what does myChar have to do with this?
      {
         word_number++;
      }
          
      total_words = word_number+1; // don't get it
   }

Why make it so complicated?

If it's a space, the character will equal ' '. No need to mess with stupid ASCII codes. [edit] And yeah, I knew the code didn't look right... [/edit] And to reference a single character from the string, just use string[subscript] . Loop for the number of the characters in the string, instead of creating an infinite loop (use strlen() to determine the length of the string).

Finally, use a single variable to add up the number of words.

This article has been dead for over six months. Start a new discussion instead.