How to make C++ Program exit as soon as we enter a specific key?

Hi all,
I am a beginner in C++ and I have a question. Please help me if you know the answer to this question.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <conio.h>

using namespace std;

int main(){

    while(true){
        cout << "Hello World" << endl;
    }

    return 0;
}


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.......

If I do it like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <conio.h>

using namespace std;

int main(){

    char key;
    while(true){
        cout << "Hello World" << endl;
        key = getch();
        if(key=='T' || key=='t'){
            break;
        }
    }

    return 0;
}


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....

Thank you,
-Himansh
Last edited on
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.
Last edited on
1
2
3
4
5
6
7
 char key;
    while(true){
        cout << "Hello World" << endl;
        key = cin.getch();                           // NOTICE: I added "cin" to read the value.
        if(key=='T' || key=='t'){
            break;
        }
@EssGeEich sorry new to this board.
It's ok, we all began from somewhere.
hmm, I see. It seems that I need to learn a lot more to accomplish this effect.
Thank you all for your kind support :)))).
-HImansh
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!
Another Website wrote:
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.
Enlighten me please... new to much of the things...
Sorry about this himansh.. but EssGeEich can you please look into my problem namely Walkies Trick
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
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...
1
2
#include <io.h>
#include <fcntl.h> 
Last edited on
@Katyayn: No need to say sorry friend, I understand...

@EssGeEich:
Thanks for writing this code, but In my IDE, It is giving some errors.
http://postimg.org/image/rzp69507r/

I can't figure out how to fix this.

-Himansh
It's a typo I did, updated post above to fix it. (Basically from eventType to EventType).
Last edited on
@EssGeEich:

Thank you , this works great. Do you know any Youtube channel which teaches event handling in C++?
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.
@EssGeEich:

Hmm, I see, Thanks for you help :)
Topic archived. No new replies allowed.