Search code examples
ccountintegercountergetchar

Counter is not incrementing properly


my counter does not seem to increment (for c programming)

int ch;
int counterX = 0;
int counterY = 0;

while(( ch = getchar()) != EOF ) {

    if (ch == 'X'){
        counterX = counterX + 1;
        }
    if (ch == 'Y'){
        counterY = counterY + 1;
        }
}

ive done some testing and I the number for counterX and counterY doesnt seem to increase, regardless of my input. Please help!


Solution

  • That should work, provided you add a closing brace, and the rest of the program. And provided you actually have X and/or Y appearing on the input stream.

    For example, the following complete program:

    #include <stdio.h>
    
    int main (void) {
        int ch, counterX = 0, counterY = 0;
    
        while ((ch = getchar()) != EOF) {
            if (ch == 'X')
                counterX = counterX + 1;
            if (ch == 'Y')
                counterY = counterY + 1;
        }
        printf ("X = %d, Y = %d\n", counterX, counterY);
        return 0;
    }
    

    will, when run with echo XYZZY | testprog, output:

    X = 1, Y = 2
    

    As an aside, if you a good enough C coder to use the:

    while ((a = something) == somethingElse)
    

    construct, you should probably know about the counterX++ shorthand as well :-)