So my program is not working and I keep changing it to figure out why. So I have two questions, can I do tracing similar to bash, and also what is wrong with this.
The idea is simple, I want to count "word" lengths, with the loose definition of word not being a space, tab, or newline. Here is what I wrote to test if it is counting words by outputting the number of 3 letter words, but it always gives 0.
#include <stdio.h>
main() {
int c, i, state, wl;
int maxlength[15];
#define IN 1
#define OUT 0
wl = i = c = 0;
state = OUT;
for (i=0; i < 15; ++i)
maxlength = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\t' || c == '\n') {
if (state == OUT)
;
else if (state == IN) {
state == OUT;
++maxlength[wl];
wl = 0;
}
else {
++wl;
state = IN;
}
}
}
printf("Number of 3 letter words: %d\n", maxlength[3]);
}
You have another error: closure of first [C]if[/C] is after last [C]else[/C] and not before:
Your code corrected:
#include <stdio.h>
main() {
int c, i, state, wl;
int maxlength[15];
#define IN 1
#define OUT 0
wl = i = c = 0;
state = OUT;
for (i=0; i < 15; ++i)
maxlength = 0;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\t' || c == '\n') {
if (state == OUT)
;
else if (state == IN) {
state == OUT;
++maxlength[wl];
wl = 0;
}
}
else {
++wl;
state = IN;
}
}
printf("Number of 3 letter words: %d\n", maxlength[3]);
}
EDIT: Script to count word sort by lenght:
sed -e 's/[\t ]/\n/g' file | awk 'length($0) {A[length($0)]++}END{for (i in A) print "word length of "i"=>"A}'
I'm not sure what you are tying to imply, but I am currently doing the classic K&M C programming language book for self study.
Answers to all questions are freely available on numerous sites, and I can and will consult them if need be, but I would rather ask here as I would rather do the "bulk" of the question myself, as in the case here. Simply consulting the answer is not very academically useful.
I generally gain useful nuggets of wisdom here that I will not gain elsewhere.
Obviously disedorgue and Corona688 did not believe that this was a homework assignment and it didn't appear to me to be one to me either, but it is close to that point where we start to wonder. When you start threads like this in the future, you might want to explicitly mention what you are doing and what prompted you to ask your question so readers won't wonder if you're asking us to do your homework for you.
Cheers,
Don
PS. What is the classic K&M C programming language book you referenced? The classic C book I usually think about is K&R C.