Hey guys, I just picked up k&r the other day and started learning C. Unfortunately, I've hit a snag early on. For some reason I can't get printf to work inside the main scope when sub-scopes are involved. I'll show you what I have (the following code is a simple word counter straight from the k&r text):
Code:
#include <stdio.h>
#define IN 1
#define OUT 0
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
If I move the printf function inside the sub-scope it becomes visible but it displays itself each time the loop runs and I end up with 10 or more instances of printf (depending on the input). As it is now, nothing is displayed after input. I had the same problem with an even simpler program (also from k&r). Am I missing something obvious?
I use code::blocks with mingw gcc if that makes any difference.