1

I am trying to figure out if there is a way to move certain characters in line while the user enters a number.

For example, I want the user to input their number between [__]. However, when the user enters the number, it will eventually overwrite the ']'. How would I move the ']' while the user enters numbers?

I am hoping I wouldn't have to loop and get single characters at a time. (I am expecting a double value)

std::cout << "Enter a number between 1 and 10: []\b\b";
std::cin >> variable;
// not sure if I should loop through individual character input from user.
4
  • Keep clearing your console. And keep rewriting a buffer where you store the updates. Commented Nov 20, 2015 at 18:29
  • @activatedgeek Wouldn't that cause flickering? Commented Nov 20, 2015 at 18:31
  • Check out ncurses. I havent used the library myself, but looks like it is what you are looking for. One of the features it has is the command to set the cursor position on the screen. Commented Nov 20, 2015 at 18:36
  • @user2970916 probably yes! Commented Nov 21, 2015 at 12:21

1 Answer 1

1

This is only possible if the console supports it, the windows console for example uses different codes to Linux.

The commands you need to send to the terminal are ANSI escape sequences and are described here:

http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html

  • Position the Cursor: \033[;H Or \033[;f puts the cursor at line L and column C.
  • Move the cursor up N lines: \033[A
  • Move the cursor down N lines: \033[B
  • Move the cursor forward N columns: \033[C
  • Move the cursor backward N columns: \033[D

So for example you could:

std::cout << "Enter a number between 1 and 10: [..]\033[D2";

(You may well need to tweak that string a bit, this isn't something I've used in a LONG time).

To print the prompt and then move the cursor.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.