getchar() not working according to the code [message #1853151] |
Mon, 20 June 2022 12:37  |
Eclipse User |
|
|
|
I am new to C language. I'm learning scanf() and getchar() statements but always have trouble while exceuting them. getchar() is not taking input as per the flow of the code, instead first the character input is taken and then rest of the code follows. For example: The code is:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
char c = 'A';
printf("%c\n",c);
printf("%d\n",c);
printf("%0x\n",c);
printf("Input a character\n");
c = getchar();
printf("You entered %c\n",c);
return EXIT_SUCCESS;
}
But the output first takes a character input and the rest of it executed, If my char input is h, the output is :
h
A
65
41
Input a character
You entered h.
I was having similar problems with scanf(), but using fflush(stdout), after scanf() statement worked. Here fflush is not working and I am not able to figure out. Please help.
|
|
|
|
|
|
Re: getchar() not working according to the code [message #1854156 is a reply to message #1853450] |
Wed, 03 August 2022 15:55  |
Eclipse User |
|
|
|
C (and other languages) use Streams for Input and Output. The streams can have buffers associated with them that prevent the transfer of data until the buffer is full, or some other action forces the transfer.
Your problem has nothing to do with scanf() or getchar(). Your issue is that the buffer for the output stream is set to some relatively large value. I think Eclipse defaults to 1000 characters. Your printf() statements are placed into the stream as expected, but nothing is transferred until the program completes because the buffer was never full.
You can find the correct setting in Eclipse to reduce the buffer size but I always advise students to choose a solution that should always work. For <stdio> you can use the command setbuf(stdout, NULL); prior to your first printf() statement. This sets the buffer size to 0 (NULL) and forces immediate transfer of the Output stream.
The reason the online compiler worked properly is that it's buffer size was set to 0 by default (which you would expect)
Note - for some embedded systems setting the buffer size to 0 can cause slowed response
|
|
|
Powered by
FUDForum. Page generated in 0.31111 seconds