• 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

    • I'm fine with a little reasonable promotion of Edge, but the degree which they do it right now I consider extremely unreasonable. 
    • Microsoft AI boss no longer believes that AI will replace human workers by David Uzondu Mustafa Suleyman, the head of Microsoft AI, recently took back his statements concerning white-collar jobs that he gave to the Financial Times in an interview made back in February, where he claimed that AI would replace office workers within 12 to 18 months. On Monday's episode of The Verge's Decoder, Suleyman recast the technology as more like a helpmate than a tool designed to take over your job. He explained that smaller office duties will "increasingly become digitized, automated" as people generate more digital materials. During the discussion, Suleyman emphasized a "very important distinction" between "tasks" and "jobs" to clarify his previous claims. He argued that his earlier comments only referred to individual actions that people perform at their desks. Suleyman used to work for DeepMind, the research lab he co-founded in 2010 alongside Demis Hassabis and Shane Legg, before he left in 2022 to establish Inflection AI and build an empathetic digital assistant. Microsoft hired him in March 2024 to lead its newly formed "Microsoft AI" division, placing him in charge of consumer products like Copilot, Bing, and Edge. His February comments also detailed plans for Microsoft to achieve self-sufficiency with a $140 billion infrastructure budget to train frontier models, predicting that creating a customized AI will soon feel like creating a podcast or a new blog: The 41-year-old is not the only AI executive who's softened his "AI will replace you" stance. OpenAI's CEO, Sam Altman, last month used X to push back against employment panic by arguing that his startup builds tools to assist humans rather than build replacements. He had previously garnered backlash by suggesting that many modern office roles that AI might replace did not qualify as "real work" in the first place, at least when you compare desk jobs to physical, historical labor like farming.
    • Adobe Acrobat Reader DC 2026.001.21662 by Razvan Serea Adobe Acrobat Reader DC software is the free, trusted standard for viewing, printing, signing, and annotating PDFs. Its the only PDF viewer that can open and interact with all types of PDF content – including forms and multimedia. It’s connected to Adobe Document Cloud – so you can work with PDFs on computers and mobile devices. Adobe Document Cloud is a revolutionary, modern and efficient way to get work done with documents in the office, at home or on-the-go. At the heart of Document Cloud is the all-new Adobe Acrobat DC, which will take e-signatures mainstream by delivering free e-signing with every individual subscription. Document Cloud includes a set of integrated services that use a consistent online profile and personal document hub. With Adobe Document Cloud, people will be able to create, review, approve, sign and track documents whether on a desktop or mobile device. Businesses will be able to take advantage of Document Cloud for enterprise which provides enterprise-class document services that integrate into systems of record such as CRM, HCM, CLM, and CMS, adding speed, efficiency and transparency to getting business done with documents. Adobe Acrobat Reader DC new feature highlights: Work with PDFs from anywhere with the new, free Acrobat DC mobile app for Android or iOS. Select functionality is also available on Windows Phone. Use the new Fill & Sign tool in your desktop software to complete PDF forms fast with smart autofill. Download the free Adobe Fill & Sign mobile app to add the same option to your iPad or Android tablet device. Save money on ink and toner when printing from your Windows PC. Store and access files in Adobe Document Cloud with 5GB of free storage. Get instant access to recent files across desktop, web, and mobile devices with Mobile Link. Sync your Fill & Sign autofill collection across desktop, web, and iPad devices. Adobe PDF Pack premium features includes: Convert documents and images to PDF files. Use your mobile device camera to take a picture of a paper document or form and convert it to PDF. Turn PDFs into editable Microsoft Word, Excel, PowerPoint, or RTF files. Combine multiple files into a single PDF (web only). Get signatures from others with a complete e-signature service. Send, track, and confirm delivery of documents electronically instead of using fax or overnight services (tracking not available on mobile). Store and access files online with 20GB of storage. Download: Adobe Acrobat Reader DC 64-bit | 719.0 MB (Freeware) Link: Adobe Acrobat Reader DC Home Page | Release Notes | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Meta will now use data from outside businesses to personalize AI responses by David Uzondu In an update that's rolling out globally (except in a handful of countries), Meta will use your data from outside businesses to personalize your AI responses and your primary feeds. Meta already utilizes your shopping activity to target ads, but the company now plans to expand this tracking to personalize other "parts of your experience" like feed algorithms and AI assistant chats. The company is replacing the two settings ("Your activity off Meta technologies" and "Activity from other businesses") that currently let you disconnect off-platform activity with a single, renamed setting called Activity from other businesses. If you don't want Meta to manipulate your feed and AI responses using your outside history, you can just turn the Activity from other businesses setting off in your account settings. This toggle resides within your Accounts Center, applying your choice to every connected profile. Turning this off will not stop companies from sending your data to Meta. The company will still collect your web interactions, but it only uses them to train products, while still accessing external accounts you connect. When The Verge spoke to Meta spokesperson, Emil Vazquez, the representative said that this update will exclude several locations at launch including the European region, the UK, Brazil, Thailand, South Africa, Turkey, South Korea, Ecuador, Nigeria, and Kenya. The new update comes at a time when the social media giant is recovering from a major PR disaster involving generative AI. Last week, there was a huge security issue on Instagram where attackers figured out a way to exploit a prompt injection vulnerability. Hackers managed to trick Meta AI into handing over account ownership (even if the victim had 2FA enabled). Some of the affected accounts include the dormant Obama White House profile, cosmetics brand Sephora, the Chief Master Sergeant of the Space Force, and security researcher Jane Manchun Wong. Internally, the company also had to scale back plans on its Model Capability Initiative (MCI), an employee-monitoring program designed to train corporate AI models by recording worker keystrokes and screen activity, after employees raised privacy concerns and complained about severe battery life drain.
    • JetBrains is working to cut false positives in RustRover 2026.2 by David Uzondu Recently, JetBrains released the fifth EAP build of its dedicated IDE, RustRover 2026.2, bringing improvements like a Run gutter icon for criterion_main! macro benchmarking and a feature that alerts you when there are unused traits in your current scope. Now, the company is out with a blog post addressing one of the "most common" complaints from users: false positives. In RustRover, a false positive occurs when the editor incorrectly highlights something as an error even though the project compiles and runs successfully. This mismatch flags a gap between the IDE's internal intelligence and the actual compiler. When the editor flashes red warnings over perfectly valid code, developers lose trust in the tool, which stalls momentum. Traditionally, RustRover runs cargo check to detect compiler errors and warnings, but it also relies on its own code analysis engine to power real-time features. To provide quick feedback, this engine parses your source code into a syntax tree while inferring types and resolving names as you type. Because this engine must work on broken, half-written code and react instantly, its logic sometimes diverges from the compiler's, producing false positives that do not exist in the compiler's eyes. JetBrains said that it has a "dedicated task force" focused specifically on identifying and fixing false positives by analyzing user reports and examining large-scale open-source projects. To speed up this process, the team built an internal system modeled after Crater, the famous Rust project that compiles and runs tests for every single crate published on crates.io. This automated pipeline compares the diagnostics from RustRover's analysis with actual compiler output to catch discrepancies before they reach users, ensuring smoother workflows. RustRover, for those who're unaware, is a dedicated IDE designed specifically for Rust developers. It's been around for a couple of years now, providing features like built-in debugging via LLDB, seamless cargo integration, advanced macro expansion, and HTML support. JetBrains distributes the app under two licensing models: a paid commercial subscription and a free option for non-commercial use.
  • Recent Achievements

    • One Year In
      Primer1st earned a badge
      One Year In
    • Experienced
      JayZJay went up a rank
      Experienced
    • Reacting Well
      Sir_Timbit earned a badge
      Reacting Well
    • Week One Done
      rubentuben8 earned a badge
      Week One Done
    • Week One Done
      ARaclen earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      512
    2. 2
      PsYcHoKiLLa
      229
    3. 3
      Edouard
      134
    4. 4
      ATLien_0
      87
    5. 5
      Steven P.
      80
  • Tell a friend

    Love Neowin? Tell a friend!