【问题标题】:Function execution until enter key is pressed函数执行直到按下回车键
【发布时间】:2017-09-15 04:47:18
【问题描述】:

我需要一个函数来继续执行,直到用户按下回车键,我在想这样的事情:

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

但我不确定这是否会导致程序在再次执行该函数之前等待用户输入某些内容,不幸的是,由于各种原因,我不能只编写它并快速测试它。这行得通吗?有没有更好的办法?

【问题讨论】:

  • 你可以递归调用function直到按下回车
  • 不,它不会工作。它将等待每次迭代的输入。 C 没有实现此目的的标准功能。
  • 第一,"\n" --> '\n'
  • 使用 fflush(stdin);在检查状况之前。检查here
  • @UsmanSajad fflush 是一个输出操作。在 stdin 上使用它具有未定义的行为。

标签: c interrupt


【解决方案1】:

使用线程程序来做同样的事情。 在这里,我正在处理主线程中的输入,并在另一个函数中循环调用该函数,该函数在自己的线程上运行,直到按下键。

在这里,我使用互斥锁来处理同步。 假设程序名称为 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() 并循环检查。

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多