0

Hi I have the following code that should echo back each character is entered.

    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;

    }

However the characters are only printed altogether when a newline is entered, and not while typing. I understand it might be a buffering issue, but how to solve?

I'am already setting

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

And manually flushing does not help.

Ukk
  • 101
  • 6
  • Terminals are typically line-based. If you want non-blocking input or per-character input then you need to use OS-specific functions to either change the terminal settings or to read the characters. – Some programmer dude Aug 20 '21 at 06:58

1 Answers1

0

first of all chInput is not initialized, it is always a good idea to do that. std::cin is used to input strings, the only function I know that allows for input of exactly one character is _getch() from conio.h

The changes to your code below ;)

#include <conio.h>
...

char chInput{ 0 };

while (chInput != '\n' && chInput != '\r') {
    //std::cin.get(chInput);
    chInput = static_cast<char>(_getch());
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19
  • `` and `_getch` are left-overs from the DOS days, and are these days Windows-specific. – Some programmer dude Aug 20 '21 at 07:37
  • You are right... seems there is already quite a bit of information here : https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed – Pepijn Kramer Aug 20 '21 at 07:54