Search code examples
cwhile-loopgetchar

Why this loop does not terminate? (C language)


I am writing a code to save input in two array a and b.

#include <stdio.h>

int tell(int *a, int *b)
{
  /* I don't know what this function does */
  return 0;
}

int main(int argc, char **argv)
{
  int i, j, a[128], b[128];

  i = 0;
  while ((a[i] = getchar()) != 10) { // 10 represents enter key
    i++;
  }
  printf("here");

  j = 0;
  while ((b[j] = getchar()) != 10) {
    j++;
    printf("here2\n");
  }

  printf("here3");
  fflush(stdout);

  if (i < j) {
    printf("here4");
    printf("%d\n", tell(a, b));
  } else {
    printf("here4");
    printf("%d\n", tell(b, a));
  }

  return 0;
}

when i input :

hello
hi

output is:

here
here2 
here2

Why "here3" does not print? The problem is not just printing here3 . I want to execute further code and it is not happening


Solution

  • The printf function will flush the output buffer when it sees \n. Try:

    printf("here3\n");
    

    You could also use:

    printf("here3");
    fflush(stdout);