【问题标题】:c++ std::cin.get() blocking std::cout until newline is entered [duplicate]c++ std::cin.get() 阻塞 std::cout 直到输入换行符
【发布时间】:2021-10-21 18:21:23
【问题描述】:

您好,我有以下代码应该回显输入的每个字符。

    std::string Utils::Input(bool fPassword)  {
        std::string strInput;

        char chInput;

        while(chInput != '\n' && chInput != '\r') {
            std::cin.get(chInput);

            if(chInput == '\t') {
                //autocomplete
            }
            else if(chInput == '\b') {
                strInput = strInput.substr(0, strInput.length() -2);
                std::cout << chInput;
            }
            else if(chInput == '\n') {
                std::cout << "\n";
            }
            else {
                strInput += chInput;
                if(!fPassword)
                    std::cout << chInput;
                else std::cout << "*";
            }

        }

        return strInput;

    }

但是,只有在输入换行符时才会完全打印字符,而不是在键入时打印。我知道这可能是一个缓冲问题,但如何解决?

我已经设置好了

std::cout.setf(std::ios::unitbuf);

手动冲洗也无济于事。

【问题讨论】:

  • 终端通常是基于行的。如果您想要非阻塞输入或按字符输入,则需要使用特定于操作系统的功能来更改终端设置或读取字符。

标签: c++ input command-line terminal


【解决方案1】:

首先 chInput 没有初始化,这样做总是一个好主意。 std::cin 用于输入字符串,我知道的唯一允许输入一个字符的函数是来自 conio.h 的 _getch()

您的代码更改如下 ;)

#include <conio.h>
...

char chInput{ 0 };

while (chInput != '\n' && chInput != '\r') {
    //std::cin.get(chInput);
    chInput = static_cast<char>(_getch());

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-11
  • 1970-01-01
  • 2010-10-12
  • 2011-07-08
  • 1970-01-01
相关资源
最近更新 更多