scanf()调用后的指令被调用两次 [英] instructions after scanf() call get called twice
问题描述
以下程序:
#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'字符处停止,
使用
parent
线程. - 为用户键入的每个字符打印消息
[input] = ..
, 使用child
线程.
- 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
在scanf
调用之后(在read
例程的循环内),
会显示两次,尽管它应该等待下一个scanf
调用中的下一个字符输入.
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.
有什么想法吗?
推荐答案
除了scanf()离开换行符的问题外,您还有其他一些小问题.
Apart from the problem of scanf() leaving newline, you have a couple of more minor issues.
-
线程函数的原型要求它们返回一个指针.因此,
read()
和child()
的末尾必须为return NULL;
(或其他值,如有必要-但我在这里看不到您有此需要).
Thread functions' prototype require they return a pointer. So
read()
andchild()
must havereturn NULL;
at the end (or other value if necessary - but I don't see you have that need here).
void main()
是main()
的非标准原型.使用int main(void)
或等效版本.
void main()
is a non-standard protype for main()
. Use int main(void)
or equivalent.
您还应该检查pthread_*
函数的返回值;他们可能会失败!
You should also check the return values of pthread_*
functions; they could fail!
在scanf(scanf(" %c", &input);
)中具有前导空格会忽略输入中 any 个空格.因此,它将消耗上一个输入留下的换行符.但总的来说,最好避免使用scanf,而最好使用fgets()
.请参见为什么每个人都说不使用scanf?我应该改用什么呢?
Having a leading whitespace in scanf( scanf(" %c", &input);
) ignores any numbers of whitespace in the input. Hence it'd consume the newline character left by the previous input. But in general, it's better to avoid scanf and prefer fgets()
instead. See Why does everyone say not to use scanf? What should I use instead?
这篇关于scanf()调用后的指令被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!