gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:54:23 25 4
gpt4 key购买 nike

以下程序:

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

问题

每条消息都具有以下模式:

begin .. end

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

有什么想法吗?

最佳答案

除了 scanf() 留下换行符的问题之外,您还有一些小问题。

  1. 线程函数的原型(prototype)要求它们返回一个指针。所以 read()child() 必须在最后有 return NULL; (或者如果需要的话其他值 - 但我没有看到你这里有这个需求)。

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

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

在 scanf( scanf("%c", &input);) 中包含前导空格会忽略输入中任何个空格。因此它会消耗先前输入留下的换行符。但一般来说,最好避免使用 scanf 并更喜欢使用 fgets() 。请参阅Why does everyone say not to use scanf? What should I use instead?

关于c - scanf() 调用后的指令被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46797239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com