kbhit if not necessarily the way to go, for starters it doesn't work in all environments -
kbhit | Microsoft Docs[
^]:
Quote:
This API cannot be used in applications that execute in the Windows Runtime. For more information, see CRT functions not supported with /ZW.
Even if you can use it, it is depreciated, and you would need
_kbhit | Microsoft Docs[
^] instead.
You use it by calling it at intervals while you go round your loop, and if true, doing something (reading the character for example) which may cause you to exit the loop.
But it's a bad solution: using a sledgehammer to crack a nut.
What you should be doing is running your long running task in a separate thread so that your UI - whatever UI environment you are running under - does not become "blocked" by the loop.
Look under the documentation for your system for "threading" and see if you can find some examples - I'd point you at some, but I have no idea what environment you are trying to work in!