在 linux 上使用 c++ 中的键退出无限循环

Exiting an infinite loop with a key in c++ on linux

我有一个无限循环,如果我按下任何键,它应该结束。该程序在 linux 中运行。我偶然发现了一个函数这是我的一些代码:

int main(){
      While(1){
        ParseData(); //writing data to a text file
      }
return 0;
}

所以我知道我可以通过在终端中使用 ctrl + c 来终止进程,但它似乎会中断写入过程,因此数据不会在进程中途完全写入。我读到我需要使用 ncurses 库中的函数,但我不太明白。

有人可以帮我吗?谢谢!

实际上C方式(包括conio.h):

char key;

while (1)
{
    key = _getch();

    // P to exit
    if (key == 'p' || key == 'P')
    {
        writer.close();
        exit(1);
    }
}

为什么你需要一个键来退出一个没有完成写入文件的程序,即使你在按键时退出循环,如果没有完成也会中断文件写入。

为什么数据写完文件就退出循环,像下面这样:

isFinished = false;      
While(!isFinished ){
    ParseData(); //writing data to a text file
   //after data finsihes
   isFinished = false;
  }

您可以声明一个 atomic_bool 并将您的主循环移动到另一个线程。现在你可以用一个简单的 cin 等待,一旦用户按下任何键你就退出循环。

std::atomic_boolean stop = false;

void loop() {
    while(!stop)
    {
        ParseData(); // your loop body here
    }
}

int main() {

    std::thread t(loop); // Separate thread for loop.

    // Wait for input character (this will suspend the main thread, but the loop
    // thread will keep running).
    std::cin.get();

    // Set the atomic boolean to true. The loop thread will exit from 
    // loop and terminate.
    stop = true;

    t.join();
    return 0;
}

thread.cpp

#include <atomic>
#include <iostream>
#include <thread>

std::atomic<bool> dataReady(false);

void waitingForWork(){
    std::cout << "Waiting... " << std::endl;
    while ( !dataReady.load() ){ 
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    std::cout << "Work done " << std::endl;
}

int main(){

  std::cout << std::endl;

  std::thread t1(waitingForWork);
  std::cout << "Press Enter to Exit" << std::endl;
  std::cin.get();

  dataReady= true; 
  t1.join();
  std::cout << "\n\n";
}

g++ -o 线程 thread.cpp -std=c++11 -pthread