簡體   English   中英

停止從標准輸入讀取

[英]stop reading from stdin

我正在用 LInux/C++ 編寫一個簡單的控制台應用程序,它接受來自命令行的用戶輸入。 我在線程中使用std::getline( std::cin ) / std::cin >> text

10 秒后,我想停止接受控制台輸入並寫一條短信,然后做其他事情。 我正在為計時器使用一個單獨的線程。

這種方法不起作用,因為在用戶沒有插入任何文本之前,我無法檢查是否已經過了 10 秒。

有沒有更好的方法來阻止應用程序接受文本和 go 到另一行? 我正在考慮使用settimer和信號編程,但為了簡單起見,我想從不同的線程調用一些東西。

問候

AFG

您可以使用ncurses ,或者如果您不想使用,可以使用select ,如本文所述。 基本上,您可以使用select並指定超時。 如果設置了 stdin FD,那么您可以安全地讀取它並且不會阻塞。 如果您想了解有關 select 的更多信息,請查看內容,當然還有Wikipedia 這是一個方便的電話了解。 例如,

// if != 0, then there is data to be read on stdin

int kbhit()
{
    // timeout structure passed into select
    struct timeval tv;
    // fd_set passed into select
    fd_set fds;
    // Set up the timeout.  here we can wait for 1 second
    tv.tv_sec = 1;
    tv.tv_usec = 0;

    // Zero out the fd_set - make sure it's pristine
    FD_ZERO(&fds);
    // Set the FD that we want to read
    FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
    // select takes the last file descriptor value + 1 in the fdset to check,
    // the fdset for reads, writes, and errors.  We are only passing in reads.
    // the last parameter is the timeout.  select will return if an FD is ready or 
    // the timeout has occurred
    select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
    // return 0 if STDIN is not ready to be read.
    return FD_ISSET(STDIN_FILENO, &fds);
}

另請參閱Peek stdin using pthreads上的這個 SO 問題

一個線程是矯枉過正。 在您的輸入循環中,使用 select() 來確定標准輸入是否已准備好讀取。 您可以通過調用 time() 檢查時間並在 10 秒后退出循環。

它工作得很好,但需要一小段代碼來“消耗”字節。

在您的kbhit()用法下方:

 int main(int argc, const char** argv ){
     while( !kbhit() ){
        // do whatever you want here while
        // entering the text
        std::cout << "..while you write!" << std::endl;
     } // stops when you hit 'ENTER'
     std::string line;
     std::getline( std::cin, line ); // consume/stores into line
     // what was written until hitting 'ENTER'
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM