1

basically what I have to do is a console program that has to read every character i'm typing and it has to store each character in a linked list while typing. However if a do a Backspace, that character has to be removed from the structure when doing it.

Is there a way or a function to do that? I'm using Windows.

Daniel López
  • 35
  • 1
  • 8
  • Certainly, there are many methods to do that. But I think to get that knowledge you may read some c++ book rather asking a question like this without knowing the fundamentals (at least as it seems) – asmmo Feb 10 '20 at 04:17
  • 2
    This is something thjat's operating-system dependent. On Linux, for example, you'll put the tty in raw mode, and handle input one character at a time. Without specifying one's operating system, no authoritative answer is possible. – Sam Varshavchik Feb 10 '20 at 04:22
  • 2
    Does this answer your question? [Capture characters from standard input without waiting for enter to be pressed](https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed) – walnut Feb 10 '20 at 04:25
  • 1
    Maybe someone could enlighten me as to why `std::cin.get()` in a loop isn't the answer? Why is this considered to be OS-dependent? Because I have an Intro assignment that uses `std::cin.get()` in a loop. – sweenish Feb 10 '20 at 05:28
  • @sweenish I think the OS dependent part is because of the backspace key. – mfnx Feb 10 '20 at 07:34
  • @sweenish the shells and consoles you type the input into buffer each line by default to allow editing, and only give it to the program when you press enter. The way to turn that off is OS-dependent. – Matt Timmermans Feb 10 '20 at 12:45

1 Answers1

0

You can use conio.h under windows. You would simply read and process any keyboard input in a while loop. Here is a simple example:

#include <conio.h>
#include <iostream>
#include <list>

int main()
{
    std::list<char> myChars; // to store what your chars
    std::cout << "START WRITING: ";
    while(true)
    {
        // read the character and perform some logic
        char val = _getch();
        if (static_cast<int>(val) == 8) // backspace: pop_back
        {
            myChars.pop_back();
            std::cout << "\b" << " " << "\b";
            /* no idea how to go up to the previous line in a console :( */
        }
        else if (static_cast<int>(val) == 13) // enter/return: new line
        {
            myChars.push_back('\n');
            std::cout << "\n";
        }
        else if (static_cast<int>(val) == 27) // escape: exit
        {
            break;
        }
        else // push_back
        {
            myChars.push_back(val);
            std::cout << val;
        }
    }
mfnx
  • 2,894
  • 1
  • 12
  • 28