I'm a total C n00b trying to teach myself C off K&R. My question is kind of embarrassingly elementary. OK, here goes: I can't get programs using getchar to give the kind of output I expected. If you happen to have K&R on hand, I'm stuck on exercise 1.13. The question goes, "Write a program to print a histogram of the lengths of words in its input. " and I can't even tackle the horizontal version because of this issue I'm having.
I'm on XP using Dev-C++ (mingW compiler) and running programs off the command line. My issue is, when I try to run my program, it waits for me to enter characters to scan from, but when I'm done inputting and hit Enter, it doesn't do anything. I expect it to go ahead and print the histogram as I expected. In reality, it doesn't even seem to count up word lengths, because as you can see in the code, when I try to print what's in the ctr array just to see if it contains anything, nothing prints.
I'm so n00b that I have no idea if it's my code or the command line that's at fault. But I suspect it's something with the system, because when I try to compile and run a model program, the same thing happens. Type in input, hit Enter, nothing happens. If I Ctrl-C, sometimes it spits out an asterisk or two that looks nothing like the model output. Other times, it doesn't do anything (just goes right back to the prompt).
Here's my code for the exercise. I've spent an entire day on this and am questioning my ability to carry on with programming. I'd really, really appreciate it if anyone could get me out of this hole!
Also, I have another question about the model program I mentioned above, but I think I should post it in its own question. Thanks all :)
#include <stdio.h>
//#define 1 IN
//#define 0 OUT
int main () {
//start w/ state = OUT
int c = 0;
// int state = OUT;
int len = 0;
int ctr[12];
int i, j;
i = j = 0;
for (i = 0; i <12; i++)
ctr[i] = 0;
while ((c = getchar()) != EOF)
if (c != ' ' && c != '\t' && c != '\n') {
// state = IN;
len++;
printf("%d", len);
}
else {
ctr[len]++;
len = 0;
}
for (i = 0; i <12; i++)
printf("%d\n", ctr[i]);
for (i = 0; i <12; i++) {
printf("%d\n", i);
for (j = 0; j <= ctr[i]; j++)
printf("-");
printf("\n");
}
return 0;
}