3
我需要一個函數繼續執行,直到用戶按下回車鍵時,我想的是這樣的:功能執行,直到輸入鍵被按下
do{
function();
} while(getchar() != "\n");
,但我不知道如果韓元」導致程序在再次執行函數之前等待用戶輸入某些內容,不幸的是,由於各種原因,我不能直接編寫它並快速測試它。這會工作嗎?有沒有更好的辦法?
我需要一個函數繼續執行,直到用戶按下回車鍵時,我想的是這樣的:功能執行,直到輸入鍵被按下
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