BDS
BDS

Reputation: 97

Printing number of input character given

I was working on an exercise program from The C Programming Language by K&R. I want to print the length of the words in the input and I am printing the length with the character 'X'.

#include<stdio.h>

void main ()
{
    int c,a[20];
    int j,k,i=0;
    int ch;
    int count,count1;

    while((c = getchar()) != EOF)
    {
        if(c == ' ' || c == '\n' || c == '\b')
        {
            ++i;
            a[i] = count;
            k = i;
            count = 0;
        }
        else
        {
            ++count;
        }
    }

    for(i = 0; i < k; i++)
    {
        count1 = a[i];

        for(j = 0; j < count1; j++)
        {
            printf("x");
        }

        printf("\n");
    }

    printf("\n");
}

Upvotes: 0

Views: 71

Answers (1)

skrtbhtngr
skrtbhtngr

Reputation: 2251

You should also use a state variable which tells if you are currently inside a word or not.

Try:

state=OUT;
len=0;
max=-1;
while((c=getchar())!=EOF)
{
    if( (c==' '||c=='\n'||c=='\t') && state==IN)
    {
        state=OUT;
        l[len-1]++;
        if(l[len-1]>max)
                max=l[len-1];
        len=0;
    }
    else
    {
        state=IN;
        len++;
    }
}

PS: OUT and IN are symbolic constants which can have any but different values. Also, you have to increment the element in array which matches the length (l[len-1]++).

Upvotes: 1

Related Questions