Question

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

Était-ce utile?

La solution 2

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

printf("here3\n");

You could also use:

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

Autres conseils

Don't do this.

Use scanf(), or fgets() or getline() to read strings from the input.

Also, never write 10 when you mean \n, it's just not the same thing and the former is way worse. Also realize that getchar() can return EOF, which does not fit in a char and will wreak some havoc on your program.

That said, I can't spot an error that explains the behavior you're claiming. Re-write it anyway.

The second loop prints here2 once for each character in the second string, so here2prints twice.

stdout is line buffered, which means that here3 won't be visible until you either print a newline or fflush(stdout).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top