This question already has an answer here:
- scanf() leaves the new line char in the buffer 4 answers
The following program:
#include <stdio.h>
#include <pthread.h>
char input;
void *
dpy(void *args)
{
printf("\n[input] = %c\n", input);
}
void *
read(void *args)
{
pthread_t child;
printf("Write whatever - press 'F' to end\n");
do
{
scanf("%c", &input);
printf("begin\n");
pthread_create(&child, NULL, dpy, NULL);
pthread_join(child, NULL);
printf("end\n");
}
while (input!='F');
printf("done\n");
}
void
main ()
{
pthread_t parent;
pthread_create(&parent, NULL, read, NULL);
pthread_join(parent, NULL);
}
- reads characters from standard input and stops at the 'F' character,
using the
parent
thread. - prints the message
[input] = ..
for each character the user types, using thechild
thread.
Problem
each message having the following pattern:
begin .. end
gets displayed twice after scanf
call (which is within the loop at the read
routine), although it is supposed to wait for the next character input from the next scanf
call.
Any thoughts?