我对编程并不陌生,但我对 C++ 比较陌生。我想分发简单的控制台应用程序,以便在学习时帮助其他人。我大学校园里的绝大多数机器都是基于 Windows 的,并且默认安装了 Borland 编译器。我更喜欢使用 g++ 和其他工具在基于 Linux 的系统上进行开发。所以我想添加一些跨平台的方式让程序运行直到用户按下回车键。这样,即使他或她双击 exe 而不是在 Windows 的控制台中运行它,用户也能够查看输出。为此,我写了类似的东西:
#include <iostream>
using namespace std;
int main()
{
float val1, val2;
bool wait = true;
cout << "Please enter the first value to add: ";
cin >> val1;
cout << "Please enter the second value to add: ";
cin >> val2;
cout << "Result: " << val1 + val2 << endl << endl;
cout << "Press enter to exit...";
while (wait)
{
if (cin.get() == '\n')
wait = false;
}
return 0;
}
使用上面的代码,程序在显示结果后退出。但是,如果您注释掉 cin 调用,它会按预期工作。这让我相信 cin.getline 正在从我上次输入的数据中提取我的输入键。我怀疑这是由于环的紧密性。我了解到 C++ 中没有跨平台的睡眠功能,所以这不是一个选择。我还能做些什么来完成这项工作?