使用标准库中的代码阻止输出在 Turbo C++ 中退出



这里的许多人告诉我停止使用clrscr()getch()等,我已经开始学习使用标准库C++,现在我想遵循标准库,我将如何在运行后立即停止输出?

include <iostream.h>
include <conio.h> // Instead of using this
    void main(){
        cout << "Hello World!" << endl;
        getch(); // Instead of using this
        }

您可以直接从命令行运行二进制文件。在这种情况下,程序执行完成后,输出仍将在终端中,您可以看到它。

否则,如果您使用的是在执行完成后立即关闭终端的 IDE,则可以使用任何阻塞操作。最简单的是scanf (" %c", &dummy);cin >> dummy;甚至getchar ();以及阿德里亚诺的建议。虽然你需要按 输入 键,因为这些是缓冲输入操作。

只需将getch()替换为如下所示的cin.get()

include <iostream>
using namespace std;
void main()
{
    cout << "Hello World!" << endl;
    cin.get();
}

有关更多详细信息,请参阅 get() 函数文档。仅供参考,您可以这样做,例如,等到用户按下特定字符:

void main()
{
    cout << "Hello World!" << endl;
    cout << "Press Q to quit." << endl;
    cin.ignore(numeric_limits<streamsize>::max(), 'Q');
}

最新更新