Thread: C noob needs help with reading words from a file and printing them with a word count

  1. #1
    Registered User
    Join Date
    Apr 2011

    C noob needs help with reading words from a file and printing them with a word count

    Hello, this is my first post here. I know literally no one else that can help me.

    I'm trying to read the words from a file and printing them out along with the number of the word. For example - if the file said "Hello my name is Meelad" the output would look like this

    Hello 1
    my 2
    name 3
    is 4
    Meelad 5

    This is my code :

    int make_dictionary(char *fname)
    	FILE *fp;                                                         /* File open* */
    	fp = fopen(fname, "r");
    	char c;                                                           /* Variable for getc() */
    	char phrase[101];                                                 /* String holder */
    	int wordcount = 1;                                                /* Word counter */
    	int i;                                                            /* Character counter */
    	if( fp == NULL )
            printf( "Oops! Could not open the file %s\n", fname );
    	for(i = 0; (c = getc(fp)) != EOF; i++)
            if( c == EOF )
    			break;                                                     /* End of file! */
            else if(isalpha(c) != 0)
    			phrase[i] = c;
    			printf("%s", phrase);
    			printf(" %d\n", wordcount);
    		else if(isalpha(c) == 0)
    			phrase[i] = '\0';
    			i = 0;
    	return wordcount;
    int main()
    	return 0;
    My output is far different, it's posting special characters and I don't know why because, as I said before, am a C noob. If this is breaking any of the rules, let me know.

    Edit: This is a homework assignment, but this is just a small portion of it that I can't get to work correctly.

    Edit2: I'm also not sure about what to do when there's multiple non alphabetic characters in a row.

    Edit3: I think I may have found out the answer. Sorry if this is spam now, I can't find out how to delete the post :\
    Last edited by Meelad360; 04-27-2011 at 10:17 PM. Reason: Clarifying

  2. #2
    Join Date
    Aug 2010
    Ontario Canada
    Edit 4: Please make up your mind!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Word Count
    By simple in forum C Programming
    Replies: 12
    Last Post: 10-04-2002, 10:47 PM
  2. reading word from file
    By stormbringer in forum C Programming
    Replies: 4
    Last Post: 07-16-2002, 12:50 PM
  3. Help reading text file word by word
    By Unregistered in forum C++ Programming
    Replies: 6
    Last Post: 05-25-2002, 05:13 PM
  4. Again Character Count, Word Count and String Search
    By client in forum C Programming
    Replies: 2
    Last Post: 05-09-2002, 11:40 AM
  5. Replies: 2
    Last Post: 05-05-2002, 01:38 PM