Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scanf()调用后的指令会被调用两次_C_Loops_Io_Pthreads_Scanf - Fatal编程技术网

scanf()调用后的指令会被调用两次

scanf()调用后的指令会被调用两次,c,loops,io,pthreads,scanf,C,Loops,Io,Pthreads,Scanf,以下节目: #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");

以下节目:

#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);
}
从标准输入读取字符并在“F”字符处停止, 使用父线程。 打印消息[输入]=。。对于用户键入的每个字符, 使用子线程。 问题 每条消息具有以下模式:

开始。。结束

在读取例程的循环中的scanf调用后显示两次,尽管它应该等待来自下一个scanf调用的下一个字符输入


有什么想法吗?

除了scanf离开新线的问题之外,您还有几个小问题

线程函数的原型要求它们返回指针。所以read和child必须返回NULL;如果需要的话,在结尾或其他值-但我看不出你有这种需要

void main是main的非标准原型。使用int mainvoid或等效工具

您还应该检查pthread_*函数的返回值;他们可能会失败

scanf scanf%c中有前导空格,&input;忽略输入中任意数量的空白。因此,它将使用上一次输入留下的换行符。但总的来说,最好避免使用scanf,而选择FGET。看