仅从cin读取一个字符 [英] Read only one char from cin

查看:253
本文介绍了仅从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 !

我想阅读char by char,并在用户在终端中键入时对每个char做一些说明。

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 != '\n'){
        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读取一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆