• 0

[C++] Implement press any key to continue


Question

How to implement press any key to continue?

The following doesn't work, it requires me to press enter.

void pressAnyKeyToContinue()
{
	cin.sync();
	cout << endl << "Press any key to continue..." << endl;
	cin.get();
}

Neither does getchar(); instead on cin.get();

15 answers to this question

Recommended Posts

  • 0

What platform are you using?

Without implementing some kind of keyboard hook, I think it's only possible on Windows.:

A) system("pause") - which will make people rant about how "slow" and unreliable it is (but you don't give a **** since you just want to end the program)

B) use the _getch function, which is included in conio.h

  • 0

What platform are you using?

Without implementing some kind of keyboard hook, I think it's only possible on Windows:

A) system("pause") - which will make people rant about how "slow" it is (like you give a **** since you just want to end the program)

B) use the _getch function, which is included in conio.h

Getch(); would work great for you. Though "cin" should already be waiting...but I think your problem is that cin.get(); waits for a specific key (Default Enter)

  • 0

Keep your original code, just change the message to "Press ENTER to continue". Both system("pause") and _getch() are Windows-specific; don't introduce that dependency just for the sake of supporting any key (if you already have that dependency, nevermind). In any case, most users press space or enter when prompted for any key.

  • 0

Keep your original code, just change the message to "Press ENTER to continue". Both system("pause") and _getch() are Windows-specific; don't introduce that dependency just for the sake of supporting any key (if you already have that dependency, nevermind). In any case, most users press space or enter when prompted for any key.

Your argument is made ad infinitum on the web, but it simply doesn't address the OP's question. He wants the user to be able to press any key, not the enter key. And I clearly pointed out that those 2 functions were Windows-specific. But if that's the platform he's developing on, then like you mention, it's perfectly fine. If not, then what he's asking is probably not possible without implementing some low-level key-event hook, but I doubt that would be cross-platform so we'd gain nothing there anyway.
  • 0

It's worth considering both. If it's homework or something, it might be best to simply ask the user to press enter, because this can be done in a cross-platform manner.

If you really want the any key thing and this is for Windows, use boogerjones' option B. There is no good reason to call pause, even if the overhead doesn't really matter. _getch() does the same thing. Remember that you probably want to flush stdin before you call it, otherwise you can end up just reading a character that is already in the buffer instead of prompting for a new one.

If it's for another platform, you would have to find out what the equivalent terminal I/O stuff is there.

  • 0

I see.. Well this then is a pretty difficult problem to overcome. Although ultimately it doesn't really matter much that you have a "press any key to continue" sort of function.

Although.. could he perhaps do something like

int main()
{
char c;
//....code.....
//...more code...
cout << "Press any key to continue.\n";
cin >> c;
//..more code
cout << "I dont know why I have so many pauses here...\n";
cin >> c;
//...etc...
}

Something like this. Just create a character to be used in the "pause" mechanism that comes with getting input.

It's not flawless, but you could just disregard the character otherwise. It only takes up one byte, anyway.

It's still not perfect but hey, do what you can.

  • 0

I think this should work:

#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int main()
{
char x = ' ';

printf("Press any key to continue...\n");
x = getch();

printf("The key you entered is: %c \n", x);

return 0;
}

int getch(void)
{
int ch;
struct termios oldt;
struct termios newt;
tcgetattr(STDIN_FILENO, &oldt); /*store old settings */
newt = oldt; /* copy old settings to new settings */
newt.c_lflag &= ~(ICANON | ECHO); /* make one change to old settings in new settings */
tcsetattr(STDIN_FILENO, TCSANOW, &newt); /*apply the new settings immediatly */
ch = getchar(); /* standard getchar call */
tcsetattr(STDIN_FILENO, TCSANOW, &oldt); /*reapply the old settings */
return ch; /*return received char */
}

I found it here: http://ubuntuforums.org/archive/index.php/t-225713.html

  • 0

Something like this. Just create a character to be used in the "pause" mechanism that comes with getting input.

It's not flawless, but you could just disregard the character otherwise. It only takes up one byte, anyway.

It's still not perfect but hey, do what you can.

No, it won't work. It will block at the first cin until you hit enter.

Rudy's code probably will work for the specific platform it's designed for (Linux?), as it's basically an implementation of the Windows _getch().

  • 0

No, it won't work. It will block at the first cin until you hit enter.

Rudy's code probably will work for the specific platform it's designed for (Linux?), as it's basically an implementation of the Windows _getch().

Unfortunately I don't have a c/c++ compiler on my Windows machine at work.... so I can't test it but yes I believe it was written for Linux (but I figured it might work on Windows or give him an idea where to start)

  • 0

Unfortunately I don't have a c/c++ compiler on my Windows machine at work.... so I can't test it but yes I believe it was written for Linux (but I figured it might work on Windows or give him an idea where to start)

It won't, because the Windows console is completely different. Still good to have though, since he didn't specify an OS.

The Windows implementation I described earlier would look like this (in C):

void pause(void)
{
	puts("Press any key to continue...");
	FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
	_getch();
}

If you wanted it to run on both Windows and Linux, you'd just have to add some #ifdefs.

  • 0
Your argument is made ad infinitum on the web, but it simply doesn't address the OP's question. He wants the user to be able to press any key, not the enter key.
No need to be so picky. I was not trying to contradict you, just propose an alternative - since you did not mention it, did you? ;). While "Press ENTER to continue" is technically not the same as "Press any key to continue", in many cases it achieves almost the same effect while avoiding a dependency on a non-standard C++ feature. Chances are the OP hadn't thought of it and might consider it a worthy solution. Of course your reply did address his point more directly, but since you already had done so, I saw no reason to repeat what you said.

That's all. :)

  • 0

The code needs to be portable, but I can work with the all your responses.

Right, then you have to just ask for enter. There is no portable way to ask for "any" key. It simply doesn't exist. I suppose you could use #ifdefs to add the platform-specific code for the platforms you support and have tested, and then fall back to asking for just enter on all other platforms.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Still 93% off: Microsoft Visual Studio Professional 2026 lifetime digital license by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where for a limited time you can still save 93% on Microsoft Visual Studio Professional 2026. Code Faster, Work Smarter with Visual Studio 2026 Visual Studio Professional 2026 is a fully featured development environment that developers around the world know & love — now enhanced with deeper AI integration, improved performance & more powerful collaboration tools. Built as a 64-bit IDE, it makes it easier than ever to work with very large solutions & complex workloads. Boost your productivity, write high-quality code & re-imagine team collaboration with an advanced suite of tools & built-in integrations designed to tackle the most demanding development workflows & deliver modern, cloud-connected applications. Build across languages and platforms Craft cross-platform mobile & desktop apps with .NET MAUI Build responsive Web UIs in C# with Blazor Build, debug, & test .NET & C++ apps targeting Windows, Linux & containers Use hot reload capabilities across .NET & C++ apps to apply code changes instantly Edit running ASP.NET/ASP.NET Core pages in the web designer view Integrate seamlessly with Azure, GitHub & other DevOps workflows Type less, code more with Intellicode and AI Understand your code context: variable names, functions, libraries & the type of code you’re writing Complete a line or block of code based on patterns learned from your codebase Get a ranked list of next best suggestions, helping you code more rapidly & accurately Use built-in AI-assisted refactoring & code suggestions to reduce bugs & boilerplate Gain deep insights into your code with codelens Reveal crucial information such as recent changes, authors, tests & commit history directly in the editor See test status & references without leaving your code Make informed decisions with a comprehensive overview of your codebase and activity Collaborate seamlessly with live share Run real-time collaboration sessions with teammates — no need for them to clone repos or install all dependencies Speed up your team’s edit & debugging cycles with personalized sessions, access controls & custom editor settings Keep everyone aligned so your team’s code stays consistent & maintainable Good to know Length of access: Lifetime License type: Professional, single-user license Redemption deadline: Redeem your code within 30 days of purchase Access options: Desktop installation on supported Windows operating systems Max number of device(s): 1 Version: Visual Studio Professional 2026 Languages supported: English, Chinese (Simplified), Chinese (Traditional), Czech, French, German, Italian, Japanese, Korean, Polish, Portuguese (Brazil), Russian, Spanish, and Turkish. Updates included: Minor updates and security fixes for the 2026 Professional release channel (according to Microsoft’s lifecycle policy) Activation method: Online activation with Microsoft account required Microsoft Visual Studio Professional 2026 normally costs $499.99, but this deal can be yours for just $34.97, that's a saving of $465. For full terms, specifications, and license info please click the link below. Get Visual Studio 2026 now for just $34.97 (was $499.99) Time limited deal Although priced in U.S. dollars, this deal is available for digital purchase worldwide. Support queries If you have queries or need support for any of the Neowin Deals, please use the contact form here. Neowin Deals are managed and sold by StackCommerce who represent Neowin on an affiliate basis. Why we post these deals We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. So for those that keep moaning and complaining, be thankful we're still online for you to even do that. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • My current phone, on left, is starting to go to sleep, and not turning on, even though I press the power button 100 times. Like CPR.   I tried factory resetting it, and nothing changed. So it's the hardware failing. I currently am using Twigby as my service provider. Cheapest I can get around here. But all their phones are carp.. https://www.twigby.com/shop/twigby-phones A friend warned me about the Moto G, as his neice has one, and isn't that good at $130. Also the Samsung A15 is laughable at best. Everything else is expensive af. I want android, (hate iOS) any version, that works with Twigby, under $100, please. Refurbished/Used is OK with me, as long as it isn't beat up.   If you know the IMEI number, you can see if it works with Twigby: https://www.twigby.com/page/byod
    • i not arguing that it isnt ######, only that it does support themes lol.
    • Bulk Crap Uninstaller 6.2 by Razvan Serea Bulk Crap Uninstaller is a free (as in speech) program uninstaller. It excels at removing large amounts of applications with minimal user input. It can clean up leftovers, detect orphaned applications, run uninstallers according to premade lists, and much more. Even though BCU was made with IT pros in mind, by default it is so straight-forward that anyone can use it effortlessly! Bulk Crap Uninstaller features: Detect and uninstall Windows Store apps Uninstall multiple items at once to speed up the process (with collision prevention) Uninstall any number of applications in a single batch Minimal user input is required during uninstallation Can find and remove leftovers after uninstallation Can uninstall some apps even if they don't have any uninstallers Detects applications with damaged or missing uninstallers Adds quiet uninstall options to some uninstallers, even if they do not support them by default Uninstall lists for automation Startup manager Verification of uninstaller certificates Fully portable, settings are saved to a single file Bulk Crap Uninstaller 6.2 changelog: Features Add invalid-uninstaller view preset by @breshinotestachegira in #903 Add certificate and integrity columns to app list by @breshinotestachegira in #894 Improve Scoop custom path detection by @breshinotestachegira in #892 Fixes Improve uninstall list load error handling by @breshinotestachegira in #895 Fix tweak visibility filtering by @breshinotestachegira in #898 Fix orphaned-only view preset by @breshinotestachegira in #899 Stabilize icon handle ownership by @breshinotestachegira in #902 Fix: Use Directory.GetLastWriteTime for install date fallback by @AniketDeshmane in #908 Do not offer to send "no way to uninstall" error messages by @Klocman in #922 Ignore ERROR_BAD_CONFIGURATION when listing MSI components by @Klocman in #924 Eat InvalidOperationException coming from ListViewGroupAccessibleObject by @Klocman in #925 Harden BCU console export and size detection - Fix BCU-console export failures by @breshinotestachegira in #897 Harden registry factory parsing by @breshinotestachegira in #893 Guard startup uninstall list loading by @breshinotestachegira in #927 Clean generated files on uninstall by @One-Simon in #928 Translations Updated Hungarian translation by @titanicbobo in #875 Updated Vietnamese translations by @wanwanvxt in #918 Fix : Swedish translation causes UI overflow in some windows by @Leise-Shadow in #865 Other Fix publish script after v6.1 by @tsiakoulias in #868 Updated the localization pack Repository Moved the repository under a new BCUninstaller organization (old links still work) Added two maintainers: @hazeliscoding and @One-Simon Added PR merge rules (require up-to-date approval and CI to pass) Updated CI script to also build the launcher (only for testing, not included in artifacts) Download: Bulk Crap Uninstaller 6.2 | 8.8 MB (Open Source) Download: Bulk Crap Uninstaller Portable | 11.6 MB View: Bulk Crap Uninstaller Home Page | GitHub | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Rookie
      lamborghiniv10 went up a rank
      Rookie
    • One Month Later
      pinnclepd earned a badge
      One Month Later
    • First Post
      X-No-file earned a badge
      First Post
    • One Month Later
      johnjacobb40 earned a badge
      One Month Later
    • One Year In
      Primer1st earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      508
    2. 2
      PsYcHoKiLLa
      210
    3. 3
      +Edouard
      145
    4. 4
      Steven P.
      87
    5. 5
      ATLien_0
      81
  • Tell a friend

    Love Neowin? Tell a friend!