仅从 cin 中读取一个字符

Read only one char from cin(仅从 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 中读取一个字符

基础教程推荐