How to exit an infinite loop at your desired time

Good day!

i am having quite a trouble for searching on how to ask this on google so here is my delema.

let have a simple code here.

1
2
3
4
5
6
7
8
      int x=1,y=0;

    while(x!=0)
    {
        y++;
        system("cls");
        cout<<y;
    }


as you may have noticed it is set to an infinite loop. when you run it, its output is changing from 0 increment.

Is it possible that while the loop is running and when i input a specific char/number it would change the value of x to 0 and therefor stopping the loop.

and i dont want to cin inside the loop.

thank you :)
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
main () {
	int x=1,y=0;

    while(x!=0)
    {
        y++;
        system("cls");
        cout<<y;
        if (kbhit()) {
		x=0;
		// or break;
	}
    }
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void threadfunction()
{
    cin>>x;
}

int main()
{
    thread t1(threadfunction);


    while(x!=999)
    {

        system("cls");
        cout<<y++<<endl;
    }

t1.join();

}



solved it using multithreading :)

so when i input 999, i would exit , by simply changing the data type of x to char, solve the problem of inputing a specific character :)
Last edited on
Wow, it's new for me knox41234

multithreading, i'll try to explore it.

Thx a lot :)
Topic archived. No new replies allowed.