如何防止 cin 的控制台输出

发布于 2024-10-03 15:24:19 字数 470 浏览 3 评论 0原文

如何防止 cin 在 C++ 中打印到控制台屏幕?给出这个简单的程序:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World..." << endl;

    cin.clear();
    cout << "Press ENTER to Continue..." << endl;
    cin.ignore();

    exit(0);
}

因此,如果用户卡在键盘上,在按下 ENTER 之前不会发生任何事情。目前效果很好,但 cin 会将按键转储到控制台。我该如何防止这种行为?


编辑:我正在 Visual Studio 2010 中工作,我问这个简单的问题是因为我想要一些不特定于平台的东西。

How does one prevent cin from printing to a console screen in C++? Given this simple program:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello World..." << endl;

    cin.clear();
    cout << "Press ENTER to Continue..." << endl;
    cin.ignore();

    exit(0);
}

So if a user jams away at the keyboard, nothing will happen until ENTER is pressed. This currently works great, but cin dumps the keypresses to the console. How do I prevent this behavior?


Edit: I'm working in Visual Studio 2010, and I ask this simple question because I want something not platform specific.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

久隐师 2024-10-10 15:24:19

在 Windows 上,您需要 SetConsoleMode

没有标准的独立于平台的方法,尽管您当然可以编写自己的 disable_echo() 函数并使用 #if _WIN32#if __LINUX__提供独立于平台的接口的特定于平台的实现。

On Windows, you need SetConsoleMode.

There is no standard platform independent way, although of course you can write your own disable_echo() function and use #if _WIN32 and #if __LINUX__ to provide platform-specific implementations of a platform-independent interface.

‘画卷フ 2024-10-10 15:24:19

您需要使用 termios(3) 函数来切换 ECHO 模式。

You need to use the termios(3) functions to toggle the ECHO mode.

北城半夏 2024-10-10 15:24:19

这是不可能的。 C++,作为一种语言规范,与键盘无关——这纯粹是平台的决定,不幸的是,各个平台并没有(甚至远程)就任何与终端相关的模糊规范达成一致。

最好不要担心或依赖它。

It can't be done. C++, as a language specification, isn't about your keyboard—that's purely a decision of the platform, and unfortunately the various platforms didn't (even remotely) come close to agreeing on a specification for anything vaguely terminal-related.

Better not to worry about or rely on it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文