1

I'm trying to implement gecthar, using read, the problem is when I use my_getchar() with printf my function executes before printf.

#ifndef BUFF_SIZE
#define BUFF_SIZE 1023
#endif

int my_getchar(void)
{
    static char buff[BUFF_SIZE];
    static char *chr;
    int         ret;

    if ((ret = read(STDIN_FILENO, buff, BUFF_SIZE)) > 0)
    {
         chr = buff;
        return (*chr);
    }
    return (EOF);
}

in my main()

char c;

printf("Enter character: "); // if I put '\n' line here, it works fine
c = my_getchar();

printf("Character entered: ");
putchar(c);

How can I solve this issue?

Junius L
  • 15,881
  • 6
  • 52
  • 96
  • Better duplicate: https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – 2501 Jul 05 '16 at 09:13

1 Answers1

5

You will need to flush the output to stdout:

fflush(stdout);

https://bytes.com/topic/c/answers/629409-fflush-stdout is a similar question

printf will typically do this for you if you have a newline (as you've found) but not if you don't.

daf
  • 1,289
  • 11
  • 16