Мне нужно запустить цикл while и принимать в него ввод всякий раз, когда есть ввод. Я не новичок в C++, но это препятствие довольно сложное. Из-за соглашения о неразглашении (это школьный проект, по-видимому, какой-то секретный материал), я могу показать вам только тестовый пример.
Я хватался за соломинку, пытаясь решить проблему; попробуйте поймать, cin.get, cin.peek, if(cin.peek){}. Если кто-нибудь может указать мне в правильном направлении, я был бы очень благодарен!
Программа не критична ко времени, но функцию нужно вызывать с фиксированным интервалом. Не обязательно, чтобы код был переносимым, представлял собой комбинацию while-cin или что-то в этом роде; код будет работать только на ПК с Windows 7 или Windows 8, по крайней мере, с двухъядерным процессором.
#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;
}
Решение было основано на ссылке Джеймса Бейлби:
// 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;
}
iostream
относительно высокого уровня. - person Rook   schedule 07.11.2012cin
в ссылке Джеймса. - person Zane   schedule 07.11.2012