Run the program until user input
Apr 30, 2015 at 12:30pm UTC
Hello everybody,
I've had a doubt. Is it possible to write a code such that the program keeps running till it detects some user input. It should run without any input and should stop running when the user types anything.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include<iostream>
#include <time.h>
#include<stdlib.h>
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
using namespace std;
int main()
{
int Hour,Minute,second,i=1;
cout<<"Enter the hour : " ;
cin>>Hour;
cout<<"Enter the minute : " ;
cin>>Minute;
cout<<"Enter the second : " ;
cin>>second;
do
{
cout<<"The time is " <<Hour<<":" <<Minute<<":" <<second<<endl;
sleep(1000000);
system("clear" );
second++;
if (second>59)
{
Minute++;
second=second-60;
}
if (Minute>59)
{
Hour++;
Minute=Minute-60;
}
if (Hour>23)
{
Hour=Hour-24;
}
i++;
}while (i<1000);
}
For example,in this code, I've set it to run 1000 times. But is it possible to make it run until the user types something ?
Apr 30, 2015 at 1:03pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
#include <chrono>
#include <future>
#include <ctime>
std::string now()
{
const std::time_t t = std::time(nullptr ) ;
return std::ctime( std::addressof(t) ) ;
}
bool wait_for_user_input() { return std::cin.get() ; }
int main()
{
std::cout << "press enter to quit\n" << std::endl ;
// http://en.cppreference.com/w/cpp/thread/async
const auto future = std::async( std::launch::async, wait_for_user_input ) ;
do std::cout << now() << std::flush ;
while ( future.wait_for( std::chrono::seconds(1) ) == std::future_status::timeout ) ;
// http://en.cppreference.com/w/cpp/thread/future/wait_for
}
Topic archived. No new replies allowed.