views:

112

answers:

3

Is is possible (without external library such as boost) to prompt for input from the user, like using cin, but with a default choice that is editable by the user (without a GUI)?

For example, the program will say:

Give your input: default

and the user can press enter to use "default" or press 1 then enter to get "default1", etc.

EDIT for clarification:

What I current have in my program is providing the default in the prompt (as in one of the answer below). But I'm writing for very special cases where having a editable default is extremely time saving (and 90% of the time, all the user needs is adding a suffix to the default). I can prompt for the suffix only, but then I lost flexibility to edit the default in the other 10% of the cases.

A: 

Not easily without an external library. All terminals handle this differently — unless you want to write a lot of code, you'll need a library. I suggest you look into Ncurses.

c4757p
curses would be massive overkill for this use case
Novelocrat
+4  A: 

You may want to use GNU readline.

Matt Kane
Specifically, you want `rl_insert_text()`. Readline has some issues on OSX (http://stackoverflow.com/questions/967029/using-readlines-rlinserttext-on-osx-10-5), but you can use the similar `editline` library instead (http://devworld.apple.com/dOcUmEnTaTiOn/Darwin/Reference/ManPages/man3/editline.3.html), for which you'd want to use `el_insertstr()`.
rampion
It's a good suggestion but I rather not have external dependencies...
polyglot
+3  A: 

This is usually done slightly differently than you've described. It's fairly common (at least as I've seen) to present the default option as part of the prompt rather than after it. For example:

Please enter a year (default: 2009):

or

Do you really want to exit (N):

This has the added advantage that if the user does want to enter his/her own value rather than the default, he/she doesn't need to delete an existing value in order to do so, which is poor usability and rather frustrating, especially if dealing with a long series of questions/prompts.

It also requires no special libraries and significantly less extra code.

Jeff L
Sometimes, though, an editable default is useful - like commit messages or in git or svn, or anytime you want to present an incomplete default to the user.
rampion
This is what I have now; but I'm writing for very special cases that having a editable default is extremely time saving (and 90% of the time all the user needs is adding a suffix to the default). I can prompt for the suffix only, but then I lost flexibility to edit the default in the 10% of cases.
polyglot
Understandable.
Jeff L
@polyglot - write that into your question. The rationale is helpful.
Novelocrat