Read only one char from cin(仅从 cin 中读取一个字符)
问题描述
从 std::cin
读取时,即使我只想读取一个字符.它将等待用户插入任意数量的字符并点击 Enter
继续!
when reading from std::cin
even if I want to read only one char. It will wait for the user to insert any number of chars and hit Enter
to continue !
我想在用户在终端输入时逐个字符地读取字符并为每个字符做一些说明.
I want to read char by char and do some instructions for every char while the user is typing in the terminal.
如果我运行这个程序并输入 abcd
然后 Enter
结果将是
if I run this program and type abcd
then Enter
the result will be
abcd
abcd
但我希望它是:
aabbccdd
代码如下:
int main(){
char a;
cin >> noskipws >> a;
while(a != '
'){
cout << a;
cin >> noskipws >> a;
}
}
请问该怎么做?
推荐答案
以 C++ 友好的方式从流中读取单个字符的最佳方法是获取底层 streambuf 并使用 sgetc()/sbumpc() 方法在上面.但是,如果 cin 由终端提供(典型情况),则终端可能启用了行缓冲,因此首先需要设置终端设置以禁用行缓冲.下面的示例还禁用了输入字符时的回显.
The best way to read single characters from a stream in a C++-friendly way is to get the underlying streambuf and use the sgetc()/sbumpc() methods on it. However, if cin is supplied by a terminal (the typical case) then the terminal likely has line buffering enabled, so first you need to set the terminal settings to disable line buffering. The example below also disables echoing of the characters as they are typed.
#include <iostream> // cout, cin, streambuf, hex, endl, sgetc, sbumpc
#include <iomanip> // setw, setfill
#include <fstream> // fstream
// These inclusions required to set terminal mode.
#include <termios.h> // struct termios, tcgetattr(), tcsetattr()
#include <stdio.h> // perror(), stderr, stdin, fileno()
using namespace std;
int main(int argc, const char *argv[])
{
struct termios t;
struct termios t_saved;
// Set terminal to single character mode.
tcgetattr(fileno(stdin), &t);
t_saved = t;
t.c_lflag &= (~ICANON & ~ECHO);
t.c_cc[VTIME] = 0;
t.c_cc[VMIN] = 1;
if (tcsetattr(fileno(stdin), TCSANOW, &t) < 0) {
perror("Unable to set terminal to single character mode");
return -1;
}
// Read single characters from cin.
std::streambuf *pbuf = cin.rdbuf();
bool done = false;
while (!done) {
cout << "Enter an character (or esc to quit): " << endl;
char c;
if (pbuf->sgetc() == EOF) done = true;
c = pbuf->sbumpc();
if (c == 0x1b) {
done = true;
} else {
cout << "You entered character 0x" << setw(2) << setfill('0') << hex << int(c) << "'" << endl;
}
}
// Restore terminal mode.
if (tcsetattr(fileno(stdin), TCSANOW, &t_saved) < 0) {
perror("Unable to restore terminal mode");
return -1;
}
return 0;
}
这篇关于仅从 cin 中读取一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:仅从 cin 中读取一个字符


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01