whileループを実行し、入力があるときはいつでもそのループへの入力を受け入れる必要があります。私はC++に不慣れではありませんが、このハードルは非常に困難です。NDA(この学校のプロジェクトは明らかにいくつかの秘密のものです)のために、私はあなたにテストケースしか見せることができません。
私は問題を解決しようとしているストローを把握してきました。catch、cin.get、cin.peek、if(cin.peek){}を試してください。誰かが私を正しい方向に向けることができれば、私はとても感謝しています!
プログラムはタイムクリティカルではありませんが、関数は一定の間隔で呼び出す必要があります。コードが移植可能である必要はなく、while-cinの組み合わせなどである必要はありません。コードは、少なくともデュアルコアプロセッサを搭載したWindows7またはWindows8PCでのみ実行されます。
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int input = 0;
int pastTime, nowTime;
pastTime = nowTime = time(0);
cin >> input;
while(input != -1)
{
if(input == 1)
{
cout << "Entered 1" << endl;
//To be done instead of the two 'elses',
//bypassing interval-dependant code
}
else if(input == 2)
{
cout << "Entered 2" << endl;
//To be done instead of the interval-dependant code
}
else if(pastTime == (nowTime - 5))
{
cout << "Nothing entered." << endl;
//Needs to be done with a fixed interval.
}
nowTime = time(0);
cin >> input;
}
return 0;
}
解決策は、JamesBeilbyのリンクに基づいています。
// This program is based on counter.cpp from Boost\lib\thread\tutorial
#include <boost/thread/thread.hpp>
#include <iostream>
#include <ctime>
int timeNow = time(0);
int timePast = time(0);
void fct_one()
{
while(1) //keeps running all the time
{
if(timePast == (timeNow - 3)) // only executed once every three seconds
{
//do some stuff
timePast = time(0);
}
timeNow = time(0); // time is continuously updated
}
}
void fct_two()
{
int input = 0;
int timeTemp = time(0);
while(1) //keeps running all the time
{
std::cin >> input; // cin blocking for input
if(input == 1)
{
//do some stuff
}
if(input == 2)
{
//do some stuff
}
if(input == -1)
{
std::cout << "Program is done. ";
system("pause");
exit(1);
}
}
}
int main()
{
boost::thread_group threads;
threads.create_thread(&fct_one)
threads.create_thread(&fct_two);
threads.join_all();
return 0;
}