Pause code until a key is pressed

shyanne
shyanne used Ask the Experts™
on
I have a loop that will display lines from a file, I have 24 lines displaing then pause, and have the user hit a key on the keyboard to continue.  How do you get the program to start the loop when the user presses a key?

Thanks


sg
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
You can use a non-standard function that is usually supported via conio.h

<conio.h>
int _kbhit( void );

EOL

Commented:
Which does an excelent job at running wreck havoc on your cpu because it forces you to write your program like a realtime application.

use int _getch( void ) instead, it's also proprietary and it doesn't have the drawbacks _kbhit has.

Example:
void main()
{
     char key=0;
     while( key!=27 && key!= 3 )
     {
          key = _getch();
          cout << "Do your stuff here" << endl;
     }
}

Commented:
Another way to do this is to use a counter in your loop to count number of records, then use a simple cin.get() like:

void main()
{
    int i = 0;
    cout<<"Press any Key to start Displaying"<<endl;
    cin.get();
    while(not end of file)
    {
         cout<<(line from file);
         i++;
         if(i > 23)
         {
              i = 0;
              cout<<"Press any Key to Continue"<<endl;
              cin.get();
         }
    }
}

I guess it seems longer but it's easier for me to understand this way.

Hope one of ours helps
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

Commented:
and for windows, a simple system("pause"); is the way to go (press any key to continue thing you see all the time)
EOL

Commented:
It's probably the way to go if you want to write a "cat" with breaks after pages, but it's definitly not the way to go if you want to mimic "less" behavior.
Why should using kbhit() is dangerous,use the code,
while(!kbhit())
     ;
to check for keyboard hit.

Commented:
This question didn't show any activity for more than 21 days. I will ask Community Support to close it unless you finalize it yourself within 7 days.
You can always request to keep this question open. But remember, experts can only help if you provide feedback to their comments.
Unless there is objection or further activity,  I will suggest to accept

    "Axter"

comment(s) as an answer.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
========
Werner
Force accepted

** Mindphaser - Community Support Moderator **

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial