Jay Khandkar Jay Khandkar - 4 months ago 8
C Question

Length of words from getchar()

I'm trying to write a program in C to print the length of words entered through getchar(). Here's the code :

#include<stdio.h>

#define IN 1
#define OUT 0

int main()
{
int c, chars, state, i;
int nlength[20];

state = OUT;
chars = 0;

for (i = 0; i < 20; ++i){
nlength[i] = 0;
}


while ((c = getchar()) != EOF){
if (c != ' ' && c != '\t' && c != '\n'){
state = IN;
++chars;
}

else if (state == OUT){
++nlength[chars];
chars = 0;
}
}
if (c == EOF){
++nlength[chars];
}

printf("\nLength of words = ");

for (i = 0; i < 20; ++i){
printf(" %d", nlength[i]);
}

printf("\n");
}


It's supposed to output, for an example of an input of "aaa aaa", : 0 0 0 2 0 0 0 ... .
However, it outputs something like 0 0 0 0 0 0 1 0 0... . Can anyone tell me what's wrong with it?

Answer

In your code state is never changed to OUT, so the following lines:

 else if (state == OUT){
         ++nlength[chars];
         chars = 0;
 }

are never executed.

There are also several places which look suspicious. E.g. you never check for array boundaries. Also you do not need a state variable, you can just check if chars > 0.

Here is your code with some modifications:

#include <stdio.h>
// we can use isspace function from ctype.h
#include <ctype.h>

#define MAX_LEN 20

int main() {
  int c, chars, i;
  // this way we don't have to zero the array explicitly
  int nlength[MAX_LEN] = {0};

  chars = 0;

  for (i = 0; i < MAX_LEN; ++i) {
    nlength[i] = 0;
  }


  while ((c = getchar()) != EOF) {
    if (!isspace(c))
      ++chars;
    else {
      // if chars == 0 we increment nlength[0]
      // which is not used anyway
      if (chars < MAX_LEN)
        ++nlength[chars];
      chars = 0;
    }
  }

  // if chars == 0 we increment nlength[0]
  if (chars < MAX_LEN)
    ++nlength[chars];

  // set 0-length words element to zero
  nlength[0] = 0;

  printf("\nLength of words = ");

  for (i = 0; i < MAX_LEN; ++i) {
    printf(" %d", nlength[i]);
  }

  printf("\n");
}
Comments