Issue
This Content is from Stack Overflow. Question asked by amixakir
Hi i need to take only 5 bytes from stdin, i’ve tried this but i have problem while executing it since it keeps asking me for input and at the end the string contained in buffer is wrong.
Also i’d like to know how to synchronize N processes while the parent is sleeping.
for(j = 0; j < 5; j++)
buffers[i][j] = getchar();
buffers[] is an array of buffers.
Solution
Note that in case stdin is associated with a terminal, there may also be input buffering in the terminal driver, entirely unrelated to stdio buffering. (Indeed, normally terminal input is line buffered in the kernel.) This kernel input handling can be modified using calls like tcsetattr(3); (stdin(3) man page)
If you give it the input "12345\n":
#include <stdio.h>
int main(void) {
char buffers[1][5];
unsigned i = 0;
for(unsigned j = 0; j < 5; j++)
buffers[i][j] = getchar();
printf("%.5s", buffers[i]);
// read the newline. You may need to discard others.
int ch = getchar();
if(ch == '\n')
printf("\n");
return 0;
}
it will print:
12345
This Question was asked in StackOverflow by amixakir and Answered by Allan Wind It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.