Alternative to system(“Pause”); revisited

2019-07-22 12:38发布

问题:

I know this question has been asked a million times, but I have a coding question with it, because a couple of alternatives seem not to work with this code, and I'm not sure why. If you look right before the return 0;, I'm trying cin.get() and it doesn't stop the program, and neither does my PressEnterToContinue() function that I found somewhere that worked on other programs. The only thing I've gotten to work with this is system pause, which I don't want to use, since I will also be using this cross platform. Any ideas?

#include <iostream>

using namespace std;

void PressEnterToContinue()
{

std::cout << "Press ENTER to continue... " << std::flush;
std::cin.ignore(std::numeric_limits <std::streamsize> ::max(), '\n');

}

int main(void)
{
int pause;
double distance, x1, y1, x2, y2, x, y;

cout << "This program outputs the distance between two points on a plane!" << endl;
cout << "Please input point X1" << endl;
cin >> x1;
cout << "Please input point Y1" << endl;
cin >> y1;
cout << "Please input point X2" << endl;
cin >> x2;
cout << "Please input point Y2" << endl;
cin >> y2;

x = x2 - x1;
y = y2 - y1;


distance = sqrt(x*x + y*y);


cout << distance << endl;

//cin.get();
    //PressEnterToContinue();
    //system("Pause");
return 0;

}

Feel free to mention methods of stopping the system that I don't have here. Thanks,

回答1:

It's because your last input (cin >> y2) leaves the newline in the input buffer. This is then read by your calls to cin.get() or PressEnterToContinue().

In the PressEnterToContinue function you might want to "peek" at the input buffer to see if there is any characters first, and if there is then do an extra cin.ignore.


When you do e.g.

cin >> y2;

And you enter the input

123\n

Then the input buffer will contain the string "123\n". After the input operator extracts the number (123) the input buffer will contain "\n", which is that the cin.get() call reads.



回答2:

To solve this problem, you simply have to flush the buffer. The number 10000 in the example is just the number of characters to clear from the buffer.

cin.ignore(10000);
cin.get();

And to answer why cin >> y2 leaves a newline character in the buffer is because you entered a newline character by hitting the return key, and by retrieving the data from the console into your variable you leave the newline character behind.



回答3:

Technical problem: characters (sometimes just a newline) left in the input buffer.

That said, there is never any need for the program stopping itself at the end, so a system( "pause" ) or whatever stopping action has no advantage, and some problems, including portability.

Run your program from the command line.

Or, since you're programming in Windows, use Visual Studio and run the program via Ctrl F5.

Or, place a breakpoint on the last right brace of main and run the program via a debugger, e.g. in visual studio by hitting F5.