Reputation: 341
i am currently working through K&R, and i have become stuck, after searching the web, trying again, and searching some more i have come to stackoverflow for help!
the task is to creae a histogram which aggregates the number of letters in each word and then display the information as a histogram.
I have figured out the histogram part, but i am having trouble counting the words.
When i enter a few words then press Ctrl+D to send EOF, and print the number of occurences of each character input; i am returned with a large value at index[0] noramlly arround '15773951'
just to clarify my code will keep adding to wc, the value used to count characters until a space, newline or tab is found.it will then use an array to store the number of times each word size has occurred by incrementing the index location which is equal to the word size.
int main(void){
int c, i, status, wc;
int numbers[array_size];
wc = 0; //used to count number of chars
//innitialize array
for(i=1; i<array_size; i++)
numbers[i] = 0;
/*start counting letters*/
while((c = getchar()) != EOF){
/*check if c is a space*/
if((c=' ')||(c='\t')||(c='\n')){
numbers[wc-'1']++;
wc = 0;
}else{
++wc;
}
}
printf("word size occured: ");
for(i=0;i<array_size;i++)
printf("%d\n", numbers[i]);
}
There is the code, could anyone explain to me why this keep happening also here is an example of output:
word size occured: 15773951
0
0
0
0
0
0
0
0
0
Upvotes: 1
Views: 569
Reputation: 10262
Ok, so:
1.
// Here you subtract from wc the integer value of the
// character '1' (which is ~49)
numbers[wc-'1']++;
should be
numbers[wc-1]++;
2.
// The array starts at index 1, ignoring the very first one ie. zero
for(i=1; i<array_size; i++)
should be
for(i=0; i<array_size; i++)
3.
// Here you assign the value ' ' to the variable c, which is equivalent to do:
// if((' ')||('\t')||('\n')){ which is equivalent to do:
// if((' ' != 0)||('\t' != 0)||('\n' != 0)){ which is always true
if((c=' ')||(c='\t')||(c='\n')){
should be
if((c==' ')||(c=='\t')||(c=='\n')){
Upvotes: 4
Reputation: 12140
You are mixing assignment up with comparison for equality....
if((c=' ')||(c='\t')||(c='\n')){
should be
if((c==' ')||(c=='\t')||(c=='\n')){
Definitely you should have a compiler warning for this ... using gcc you should add -Wall to the command line so you don't have to debug this again.
See gcc warning options for details on all available warning options.
Upvotes: 2