• 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

    • HomeBank 5.10.1 by Razvan Serea HomeBank is a free software (as in "free speech" and also as in "free beer") that will assist you to manage your personal accounting. It is designed to easy to use and be able to analyse your personal finance and budget in detail using powerful filtering tools and beautiful charts. If you are looking for a completely free and easy application to manage your personal accounting, budget, finance then HomeBank should be the software of choice. HomeBank also benefits of more than 19 years of user experience and feedback, and is translated by its users in around 56 languages. Highlights: Cross platform, supports GNU/Linux, Microsoft Windows, Mac OS X Import easily from Intuit Quicken, Microsoft Money or other software Import bank account statements (OFX, QIF, CSV, QFX) Duplicate transaction detection Automatic cheque numbering Various account types : Bank, Cash, Asset, Credit card, Liability Scheduled transaction Category split Internal transfer Month/Annual budget Dynamic powerful reports with charts Automatic category/payee assignment Vehicule cost HomeBank 5.10.1 changelog: change: the input field helper icon + fixed some spacing inconsistency change: transaction, added some missing input tooltips and reworked existing change: category, payee and tag window add input now have a tooltip and button change: split window, refactored the layout change: split window, add display of memo and date wish : #2106800 budget report option to exclude transfers from unbudgeted line bugfix: prevent deletion of non pending transaction when rejecting bugfix: transaction warning for no rate faultly showing in transfer bugfix: report missing space for filter tooltip icon bugfix: budget report missing filter tooltip bugfix: manage account closed icon was hidding budget icon bugfix: #2154771 view transcations requires hitting Escape or X twice to close dialog bugfix: #2154337 transfer to/from closed account with different currency don't show the amount bugfix: #2154234 scheduled transaction recurring pattern daily value limited to 100 bugfix: #2149897 view split for closed accounts bugfix: #2148561 global time chart do not shows current period by default bugfix: #2148456 the main screen Total Chart is no longer showing an overall total bugfix: #2147497 editing a transaction resets scroll position bugfix: #2147377 balance mixup with transaction same day sort by amount bugfix: #2147052 quarter are wrong when fiscal year is jan 1 bugfix: #2147048 all events for the month are late but today is only the 1st bugfix: #2144993 impossible to search for transactions by value for values >999,99 bugfix: #2144698 adding new Category/Payee/Tags requires hitting -Enter- bugfix: #2144419 QIF Account name detection fail on import bugfix: #2142349 can't delete account groups bugfix: #2139409 account maximum limit is not fully used (example credit card) bugfix: #2133783 transfers shouldn't add to dashboard top spending reports Download: HomeBank 5.10.1 | 20.5 MB (Open Source) Download: 3rd party packages (macOSX. Ubuntu...etc) View: HomeBank Website | Support | Features | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Same, price was right for my Home, laptop, phone. Works great!
    • Brave and Firefox. I’ve been using them as my primary browsers for a while now, perfect combo
    • They want Ring 0 access. Should be a hard no. A middle ground needs to be found.
  • 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
      524
    2. 2
      PsYcHoKiLLa
      232
    3. 3
      Edouard
      135
    4. 4
      ATLien_0
      88
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!