The above program will print "Hello World" endlessly. I want that as soon the user presses the "T" key on the keyboard, the program terminates.
Any clue on how to do this.......
Then the program will always wait for the user to press a key. I want that the program continues executing without pausing, and as soon as user presses any specific key, then the program terminates.
I hope that you have understood what I am trying to say.
Waiting for your replies....
I think you cannot do that in simple way, This is just my idea but,
I think you can use EVENT HANDLING remember that this is just my idea and i don't know anything about that..
That's not how he does it anyways (He wants to KEEP printing something without waiting for the user to press a key)
As nevermore28 said, you should go into the "Event handling" world.
There's no portable way to do it, you should either specify, for Windows or Unix.
(For Windows, it's quite simple, it should require like 20 or 30 lines of code)
@ACHILL3S: You can also use the Edit button to edit your post, that will not mess up posts' orders.
So basically you want the loop to loop infinitely until you press a key... hmmm interesting......
you might want to look into the kbhit function of conio.h since you are trying this on c++.
Look this function up in the help and there you get all the help you need.
this function with some simple logic can establish the effect you want.
☺☻ Enjoy!
This function is not defined as part of the ANSI C/C++ standard. It is generally used by Borland's family of compilers.
( http://www.cprogramming.com/fod/kbhit.html )
I see he's including conio.h, but kbhit doesn't tell WHICH key is pressed, and relying on a cin.get() AFTER kbhit may have made the key go up already, making the program wait without closing, in a semi-freezed state.
In fact, if you're using Windows you should use PeekConsoleInput and ReadConsoleInput.
If you want a bigger example, just reply in another post and I will do so.
bool KeepRunning = 1;
while(KeepRunning)
{
INPUT_RECORD Event = {0};
DWORD r = 0;
HANDLE consoleHandle = GetStdHandle(STD_INPUT_HANDLE);
if(PeekConsoleInput(consoleHandle,&Event,1,&r) && r>0)
{
if(ReadConsoleInput(consoleHandle,&Event,1,&r))
{
if(Event.EventType == KEY_EVENT)
{
// It's a virtual key - You must use CAPITAL letters
if(Event.Event.KeyEvent.wVirtualKeyCode == 'T'
&& Event.Event.KeyEvent.bKeyDown != 0)
{
// This happens when the key T is pressed, even if lowercase.
// The keys won't even be shown on the console,
// because the console will be in output mode.
KeepRunning = 0;
}
}
}
}
cout << "Hello World" << endl;
}
But as you may see this is not something portable, and may have some issues with cin/cout (On all my tests, it didn't).
Make sure to #include <windows.h> .
And if that's not enough, also...
Personally, no, I don't follow YouTube tutorials as they're bandwidth intensive.
I learnt to understand how MSDN explains things, and I learnt most of those things from MSDN itself.