-3

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!

user2947725
  • 41
  • 3
  • 9
  • The code you submitted is not compilable because you missed the definition of ch and you are missing the brace enclosing the while loop - that brace could be crucial. – Angus Comber Aug 31 '14 at 10:27
  • sry this is just a rough portion of my current program that has the issue. ill edit it properly – user2947725 Aug 31 '14 at 10:30
  • Try to debug your code: http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – alk Aug 31 '14 at 10:31

1 Answers1

1

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 :-)

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953