功能执行,直到输入键被按下
问题描述:
我需要一个函数继续执行,直到用户按下回车键时,我想的是这样的:功能执行,直到输入键被按下
do{
function();
} while(getchar() != "\n");
,但我不知道如果韩元”导致程序在再次执行函数之前等待用户输入某些内容,不幸的是,由于各种原因,我不能直接编写它并快速测试它。这会工作吗?有没有更好的办法?
答
使用线程化程序也能做到这一点。 在这里,我正在处理主线程中的输入,并在另一个函数的循环中调用函数,该函数在其自己的线程上运行,直到按下键。
在这里,我使用互斥锁来处理同步。 假设程序名称为Test.c,然后使用-pthread标志“gcc Test.c -o test -pthread”进行编译,而不使用qoutes。 我假设你使用的是Ubuntu。
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
pthread_mutex_t tlock=PTHREAD_MUTEX_INITIALIZER;
pthread_t tid;
int keypressed=0;
void function()
{
printf("\nInside function");
}
void *threadFun(void *arg)
{
int condition=1;
while(condition)
{
function();
pthread_mutex_lock(&tlock);
if(keypressed==1)//Checking whether Enter input has occurred in main thread.
condition=0;
pthread_mutex_unlock(&tlock);
}
}
int main()
{
char ch;
pthread_create(&tid,NULL,&threadFun,NULL);//start threadFun in new thread
scanf("%c",&ch);
if(ch=='\n')
{
pthread_mutex_lock(&tlock);
keypressed=1;//Setting this will cause the loop in threadFun to break
pthread_mutex_unlock(&tlock);
}
pthread_join(tid,NULL);//Wait for the threadFun to complete execution
return 0;
}
如果您希望输入其他字符,您可能必须执行scanf()并检查循环。
您可以递归调用'功能'直到按下输入 – krpra
不,它不会工作。它将等待每次迭代的输入。 C没有标准功能来实现这一点。 –
首先,''\ n“' - >''\ n'' – BLUEPIXY