Another...

This is a discussion on Another... within the C Programming forums, part of the General Programming Boards category; stupid problem that I can't figure out It's a clone of the wc command in unix. My output on a ...

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    8

    Another...

    stupid problem that I can't figure out

    It's a clone of the wc command in unix.

    My output on a file:
    characters: 157138
    words: 29135
    lines: 1977

    WC output on a file:
    characters: 157138
    words: 28175
    lines: 1977

    as you can see only the words are different. Here is the latest reincarnation of my code. I've tried lots of other things, but they either gave me too few words, or even more than I have now.

    Code:
                   /* get the next character */
    	while((value = fgetc(inFile)) != EOF){
                                    /* is it a new line*/
    		if((char)value == '\n'){
                                                    /* increment line counter, charater counter*/
    			lineCount++;
    			charCount++;
    			/* i is 0 if this is the first occurence of a new line, then increment wordCount */
                                                    if(i == 0)
    				wordCount++;
    			i++;
    		}
    		if((char)value == ' '){
    			if(k == 0)
    				wordCount++;
    			k++;
    			charCount++;
    		}
    		if((char)value != ' ' && (char)value != '\n'){
    			charCount++;
                                                    /*found a new character, reset i and k*/
    			i = 0;
    			k = 0;
    		}
    	}
    I had code for a tab check too, but it didn't help either so I took it out of this one.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    With word count, you usually want something like:
    Code:
    while( x < strlen( buf ) && isspace( buf[x] ) ) x++; /* skip all preceeding white space */
    if( buf[x] )
    {
        /* we're at the start of a word */
        word++;
    }
    while( x < strlen( buf ) && !isspace( buf[x] ) ) x++; /* move through the word */
    /* we've just finished with a word */
    Something like that usually does the trick.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

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