#include <conio.h>
#include <iostream>
int main()
{
/* code */
std::cout << "Press any key to exit...";
while( ! _kbhit() )
{ /* do nothing until a key is pressed */ }
return 0;
}
This will wait for a key press before exiting the loop and returing 0 from main. No need to hit enter to continue.
// This program averages 3 test scores. It repeats as
// many times as the user wishes.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
int score1, score2, score3; // Three scores
double average; // Average score
char again; // To hold Y or N input
do
{
// Get three scores.
cout << "Enter your 3 test scores and I will average them: \n";
cin >> score1;
cin >> score2;
cin >> score3;
if (score1 < 0 || score2 < 0 || score3 < 0 )
{
cout << "Invalid input, score cannot be less than zero.\n";
continue;
}
// Calculate and display the average.
average = (score1 + score2 + score3) / 3.0;
cout << "The average is " << average << ".\n";
// Does the user want to average another set?
cout << "Do you want to average another set of scores? (Y/N) ";
cin >> again;
cout << "Press enter to close.\n";
cin.get();
} while (again == 'Y' || again == 'y');
return 0;
}
Your cin >> again leaves an endline character in the buffer, which is passed to cin.get() later on. You have to clear the buffer somehow, and protect cin.get() from input errors.
Try this function for pausing:
1 2 3 4 5 6 7
void pause()
{
std::cout << "Press ENTER to continue.";
std::cin.clear(); //clear errors
std::cin.sync(); //clear the buffer
std::cin.get();
}
Cuddlebuddie928's suggestion is good too! create a function for it, then if you want to pause more than once, you just call that function, rather than typing the code each time.
Yes his function idea would be great but i was looking for a simple line or 2 fix, so the cin.ignore/get will suffice. and no its not my topic but it definitely suited me.
cout << "Press enter to close.\n"; //pauses the program to view results before closing.
cin.ignore(); //use this to clear the buffered data from previous code, you may or may not need this.
cin.get(); // this accepts the enter key and then follows the closing code.
return 0;