替代系统(“暂停”);再访 [英] Alternative to system("Pause"); revisited

查看:174
本文介绍了替代系统(“暂停”);再访的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已被问了一百万次,但我有一个编码问题,因为一些替代品似乎无法使用这段代码,我不知道为什么。如果你看起来在返回0之前,我试图cin.get(),它不停止程序,也不是我的PressEnterToContinue()函数,我发现在其他地方工作的其他程序。我唯一需要处理的是系统暂停,我不想使用,因为我也将使用这个跨平台。任何想法?

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,

推荐答案

这是因为您最后一次输入( cin>> y2 )在输入缓冲区中离开换行符。然后通过 cin.get() PressEnterToContinue()的呼叫读取。

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().

PressEnterToContinue 函数中,您可能需要peek在输入缓冲区查看是否有任何字符,如果有,然后做一个额外的 cin.ignore

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.

当你这样做

cin >> y2;

并输入

123\n

然后输入缓冲区将包含字符串123 \\\
。输入操作符提取数字( 123 )后,输入缓冲区将包含\\\
cin.get()调用读取。

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.

这篇关于替代系统(“暂停”);再访的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆