gpt4 book ai didi

c++ - 替代系统 ("Pause");重访

转载 作者:行者123 更新时间:2023-11-30 01:19:44 27 4
gpt4 key购买 nike

我知道这个问题已被问过一百万次,但我有一个编码问题,因为有几个替代方案似乎不适用于此代码,我不确定为什么。如果你在 return 0; 之前看,我正在尝试 cin.get() 并且它不会停止程序,我在其他程序上找到的 PressEnterToContinue() 函数也不会停止。我唯一需要处理的是系统暂停,我不想使用它,因为我也将使用这个跨平台。有什么想法吗?

#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;

}

请随意提及我在这里没有的停止系统的方法。谢谢,

最佳答案

这是因为您最后的输入 (cin >> y2) 在输入缓冲区中留下了换行符。然后通过调用 cin.get()PressEnterToContinue() 读取它。

PressEnterToContinue 函数中,您可能需要 "peek"在输入缓冲区首先查看是否有任何字符,如果有则执行额外的 cin.ignore


当你这样做时

cin >> y2;

然后你输入输入

123\n

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

关于c++ - 替代系统 ("Pause");重访,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20486806/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com