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

以下程序:

#include  #include  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); } 
  1. 从标准输入读取字符并使用parent线程停在’F’​​字符处。
  2. 使用child线程为用户键入的每个字符打印消息[input] = ..

问题

每条消息都有以下模式:

开始..结束

scanf调用之后(在read例程的循环内)显示两次,尽管它应该等待下一次scanf调用的下一个字符输入。

有什么想法吗?

除了scanf()离开换行的问题,你还有一些小问题。

  1. 线程函数的原型要求它们返回一个指针。 所以read()child()必须return NULL; 最后(或其他价值,如果有必要 – 但我不认为你有这种需要)。

  2. void main()void main()的非标准原型。 使用int main(void)或等效的。

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

在scanf中有一个前导空格( scanf(" %c", &input); )忽略scanf(" %c", &input); 任何数量的空格。 因此它消耗了前一个输入留下的换行符。 但总的来说,最好避免使用scanf而不是fgets() 。 看看为什么每个人都说不使用scanf? 我该怎么用?