1

Hello everybody i am currently reading 'The C Programming Language' and while i was doing one of the exercises i couldn't solve one of them. The problem no is 1-13. It says

Write a program to print a histogram of the lengths of words in its input. It is easy so draw the histogram with bars horizontal; a vertical orientation is more challenging

So i wrote this code for the first part of the problem, counting:

#include<stdio.h>

int main(void)
{
    char c;
    int arr[100];
    while((c = getchar()) != EOF)
    {
        int i = 0;
        while(c != ' ' || c != '\t' || c != '\n')
        {
            i++;
            c = getchar();
        }
        arr[i]++;
    }
}

but i cannot get it to work, it always get's stuck in seconds while loop. This one:

while(c != ' ' || c != '\t' || c != '\n')
{
    i++;
    c = getchar();
}

Do you guys have any idea why? I've been staring at this code for 30 minutes now, a similar code worked on earlier exercises but i cannot post the code for them because i deleted them. Sorry if that causes an inconvenience.

I also looked at Print a Histogram based on word lengths (C) but i still don't know why my code doesn't work.

I compile it with gcc main.c and run it with cat main.c | ./a.out

tas_dogu
  • 11
  • 2
  • You need to check for `EOF` in the inner loop and limit the number of characters read (e.g. `i < 100`) You will need to break both loops when `EOF` is found in the inner loop; Hint, use a flag or `goto`. – David C. Rankin Mar 14 '21 at 05:51
  • Thank you very much, i'll look into it – tas_dogu Mar 14 '21 at 06:03
  • There is actually a simpler way to do it with a single loop. Just loop with your outer loop as is until `EOF`. Inside the loop keep track of whether you are in a word adding to length, or between words reading spaces (or punctuation). When you reach a space, if length is non-zero, increment that element in your histogram, e.g. `histogram[len]++'`. When done loop over your histogram and if `histogram[i]` is nonzero, print that number of `'X'` to stdout showing the number of words of that length you encountered. – David C. Rankin Mar 14 '21 at 06:11
  • If you are still stuck, see [Histogram of Word Length](https://paste.opensuse.org/18770887) implementing the single-loop approach. (example expires: Sun Apr 11 04:34:31 CDT 2021) – David C. Rankin Mar 14 '21 at 09:35
  • thank you guys so much, i've solved my issue – tas_dogu Mar 15 '21 at 06:03

0 Answers0