如何防止 cin 的控制台输出
如何防止 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 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.您需要使用
termios(3)
函数来切换ECHO
模式。You need to use the
termios(3)
functions to toggle theECHO
mode.这是不可能的。 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.