从cin只读一个字符

时间:2014-02-25 23:03:10

标签: c++ char cin

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

我想通过char读取char,并在用户在终端中输入时为每个char执行一些说明。

实施例

如果我运行此程序并输入abcd,则输入Enter,结果将为

abcd
abcd

但我希望它是:

aabbccdd

以下是代码:

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

请问怎么做?

4 个答案:

答案 0 :(得分:2)

以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;
}

答案 1 :(得分:0)

看看:

std::cin.get(char)

答案 2 :(得分:0)

C ++ cin模型是用户在终端中编写整行,在必要时进行退格和纠正,然后当他满意时,将整行提交给程序。

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

答案 3 :(得分:-1)

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
    char a;
    do{
        a=getche();
        cout<<a;
    }while(a!='\n');
    return 0;
}
相关问题