Reputation: 189
I am trying something like this.Its counting down seconds from 5-1.
#include<iostream>
#include<stdlib.h>
#include<windows.h>
#include<iomanip>
using namespace std;
int main()
{
for(int i=5;i>0;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
system("PAUSE");
}
And i trying to figure out a way to break the loop using a user input(from keyboard) to break it while its running. I have no idea about how to do this.I have heard about multi-threading. I don't even know if multi-threading has any application in my situation or not .So any ideas on how to break it in middle while its executing the loop?
Upvotes: 1
Views: 4745
Reputation: 180
I think you will need a thread to do it.
add a global variable in your main loop, use a thread to receive the command line input and modify your global variable.
declare a global variable
bool stop = false;
create a thread to read stdin and modify 'stop'
DWORD WINAPI thread1(LPVOID pm)
{
//check the getchar value
int a = getchar();
while (a != '0'){
a = getchar();
}
stop = true;
return 0;
}
in your main:
HANDLE handle = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
for(int i=5;i>0 && !stop;i--)
{
cout<<"\n\n\n\n\n\n";
cout<<setw(35);
cout<<i;
Sleep(1000);
system("CLS");
}
Upvotes: 1
Reputation: 852
Try this:
#include<iostream>
using namespace std;
int main()
{
int i = 1;
while(i)
{
// do your work here
cin>>i;
}
cout<<"Terminated"<<endl;
}
Continue scanning int i, when you want to break loop give 0 as input value and your loop will be terminatd.
Upvotes: 0