仅从 cin 读取一个字符

web*_*eat 1 c++ cin char

读取时,std::cin即使我只想读取一个字符。它将等待用户插入任意数量的字符并点击Enter继续!

我想逐个字符读取字符,并在用户在终端中键入时为每个字符执行一些说明。

例子

如果我运行这个程序并输入abcd那么Enter结果将是

abcd
abcd
Run Code Online (Sandbox Code Playgroud)

但我希望它是:

aabbccdd
Run Code Online (Sandbox Code Playgroud)

这是代码:

int main(){
    char a;
    cin >> noskipws >> a;
    while(a != '\n'){
        cout << a;
        cin >> noskipws >> a;
    }
}
Run Code Online (Sandbox Code Playgroud)

请问怎么做?

ble*_*ter 9

以 C++ 友好的方式从流中读取单个字符的最佳方法是获取底层流缓冲并在其上使用 sgetc()/sbumpc() 方法。但是,如果 cin 由终端提供(典型情况),则终端可能启用了行缓冲,因此首先您需要设置终端设置以禁用行缓冲。下面的示例还禁用了键入字符时的回显。

#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;
}
Run Code Online (Sandbox Code Playgroud)


Mal*_*ean 7

C++ cin 模型是用户在终端中编写整行,必要时退格并更正,然后当他高兴时,将整行提交给程序。

你不能轻易打破它,也不应该打破它,除非你想接管整个终端,例如,让一个小人在由按键控制的迷宫中徘徊。为此,请在 Unix 系统上使用curses.h,或在DOS 系统上使用conio.h。


小智 -1

看一眼:

std::cin.get(char)
Run Code Online (Sandbox Code Playgroud)