Search code examples
c++command-line-tool

Is it possible to prompt for user input and provide a default?


It is not uncommon to see a command-line program that prompts the user to enter a string to be processed in some way by the program. But is it possible to create a program that does this, and has a default value already there at the prompt - so that if the user wants to use the default value, they need only press Enter? (But if the user wants to use a different value, they will have to set about editing the pre-populated string - which might mean holding down backspace to delete it and then typing something else.)

Provisos:

  • Needs to work on Windows. Well, for my purposes it needs to work on Windows. You can suggest a solution that only works on other OSes if you like, but I won't accept your answer.
  • Needs to use only what is provided by the standard library.
  • It's not sufficient to just say, "leave input empty to use the default value" - that's merely a workaround.

I've seen versions of this question that are specific to other languages, but not one for C++.


Solution

  • One can do it using just the standard library.
    But one cannot do it with just the guarantees provided by the standard library.

    What you need to have, for any solution, is a way to control the terminal (which implies a guarantee about being connected to a terminal, and knowledge of the idiosyncrasies in controlling said terminal.

    Unfortunately, the windows console window is not a proper terminal, which can be controlled that way.