按Enter键无法完成do-while循环

时间:2016-11-08 13:47:32

标签: c++ loops while-loop

当我按下回车键时,我想完成我的do-while循环。你有什么想法解决这个问题吗?我试图检查ENTER键的ASCII代码,但它没有成功。

                  do{
                    for(int dongu=0;dongu<secimSayi;dongu++)
                    {
                        cout<<"-";
                        sleep(1);
                        if(dongu==secimSayi-1)
                        {
                            cout<<">"<<endl;
                        }
                    }
                    for(int dongu2=0;dongu2<secimSayi;dongu2++)
                    {
                        cout<<" ";
                    }

                    for(int dongu3=secimSayi;0<dongu3;dongu3--)
                    {

                        cout<<"-\b\b";
                        sleep(1);                               
                        if(dongu3==1)
                        {
                            cout<<"<"<<endl;

                        } 
                    }

                }while(getchar()== '\n');  //I want to end this do-while loop when I pressed ENTER

1 个答案:

答案 0 :(得分:1)

我不相信在C ++中有一个标准的解决方案,这通常不是标准控制台程序的工作方式。

最标准的方法可能是使用threads,其中一个线程等待直到读取一行,然后通过设置std::atomic<bool>向主线程发出信号。
(见例)

另一种解决方案可能是根据操作系统寻找合适的库。在linux上,您可以在Windows上使用ncurses,还有support。这也应该可以更好地控制程序的输出。

线程方法的示例:

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

class WaitForEnter
{
public:
  WaitForEnter() : finish(false)
  {
    thr = std::thread([this]() { 
        std::string in; 
        std::getline(std::cin, in);
        finish = true; 
      });
  }
  ~WaitForEnter()
  {
    thr.join();
  }
  bool isFinished() const { return finish; }
private:
  std::atomic<bool> finish;
  std::thread thr;
};

int main()
{
    WaitForEnter wait;
    while (! wait.isFinished())
    {
      std::cout << "." << std::flush;
      std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    std::cout << "\nfinished\n";
}