【问题标题】:instructions after scanf() call get called twice [duplicate]scanf()调用后的指令被调用两次[重复]
【发布时间】:2018-03-29 13:32:07
【问题描述】:

以下程序:

#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 线程。

问题

每条消息具有以下模式:

开始..结束

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

有什么想法吗?

【问题讨论】:

    标签: c loops io pthreads scanf


    【解决方案1】:

    除了 scanf() 离开换行符的问题之外,您还有几个小问题。

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-04-02
      • 2017-06-19
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 2021-07-12
      • 2017-03-15
      相关资源
      最近更新 更多