idelara
idelara

Reputation: 1816

Word counter getting negative value in C

I am trying to develop this word counter (along with line and char counters as well). The rules are that everything is a word except anything separated by spaces, tabs, new lines, semicolons and hyphens. For example: 'xyz' 'go;down' 'hey..howareyou' are all 1 word each and 'hey:you' 'tacos-burrito' are each 2 words.

My approach is the following:

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

int main(){

    int charHolder, result, wordCount, lineCount = 0;

    int recursiveSeparatorCheck(charOther){
        if(isspace(charOther)||charOther=='\t'||charOther=='\n' || charOther ==':' || charOther == '-')
            return 1;
        return 0; 
    }


    while ((charHolder = getchar()) != EOF){
        if(charHolder == '\n')
            lineCount++;
        result++;
        if(recursiveSeparatorCheck(charHolder) == 1)
            continue;
        wordCount++;


    }


    printf("Number of char: %d \n", result);
    printf("Number of lines: %d \n", lineCount);
    printf("Number of words: %d \n", wordCount);
    return (EXIT_SUCCESS);
}

When I run my program and feed it to read a file that has 20 lines and 160 words, it prints the following:

Number of char: 1130 
Number of lines: 20 
Number of words: -4195164 

Does anybody know what am I doing wrong? Thanks for your help!

Upvotes: 0

Views: 92

Answers (3)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

wordCount is uninitialized, an it contains indeterminate value, you need to explicitly initialize it to 0, as well as all other variables

int charHolder, result, wordCount, lineCount = 0;

is only initializing lineCount, for it to work you need something like this

int charHolder, result, wordCount, lineCount;
charHolder = result = wordCount = lineCount = 0;

which I don't like at all, but it seems that this is what you meant.

Note: You really need to use compiler warnings.

Upvotes: 2

Arkku
Arkku

Reputation: 42139

It seems that you are under the impression that this line initialises all four variables to 0:

int charHolder, result, wordCount, lineCount = 0;

It doesn't. Only lineCount is initialised, the rest have undefined values. Add = 0 after wordCount and result to initialise them.

Upvotes: 3

paulsm4
paulsm4

Reputation: 121659

You should try this:

int charHolder = 0, result = 0, wordCount = 0, lineCount = 0;

Upvotes: 0

Related Questions