3

I need a function to continue executing until the user presses the enter key, I'm thinking of something like:

do{
   function();
} while(getchar() != "\n");

but I'm not sure if that won't cause the program to wait for the user to input something before it executes the function again and unfortunately, for various reasons, I cannot just write it and quickly test it. Will this work? Is there a better way?

M Russell
  • 35
  • 5

1 Answers1

0

Use a threaded program to do the same . Here I am handling the input in the main thread and calling the function in a loop in another function which runs on its own thread until key is pressed.

Here , I am using mutex lock to handle synchronisation . Suppose the Program name is Test.c , then compile with -pthread flag "gcc Test.c -o test -pthread" without qoutes. I am assuming you are using 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;
}

You may have to perform the scanf() and checking in a loop if you expect other characters to be input.