c++ - 从 cin 中只读取一个字符

标签 c++ char cin

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

我想一个字符一个字符地读取,并在用户在终端中输入时为每个字符执行一些指令。

例子

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

abcd
abcd

但我希望它是:

aabbccdd

代码如下:

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

请问怎么做?

最佳答案

以 C++ 友好的方式从流中读取单个字符的最佳方法是获取底层 streambuf 并在其上使用 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;
}

关于c++ - 从 cin 中只读取一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22028142/

相关文章:

c++ - 这个 C++ 项目可以用 .NET Reflector 之类的工具反编译吗?

c++ - 链接器找不到导入的 DLL 的 LIB 文件

c++ - 在同一变量上混合后置和前置递增/递减运算符

使用 strtok_s 从 char* 文本创建动态 char* 数组

C++ cin.getline 只读取一个字符

c++ - 断言失败,列表迭代器不可取消引用

关于 char** 参数的 const char** 参数警告

c++ - itoa 会删除字符吗?

c++ - 可能有多个 while (cin>>input)

c++ - 如何在不中断剩余代码的情况下仅 cin C++ 中的整数?