Reputation: 16122
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?
Upvotes: 1
Views: 888
Reputation: 1329
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.
Upvotes: 5