Kain
Kain

Reputation: 359

clearing the current line in the console in c

How can i clear the current line or any line in the console using c ?

Enter a number (waiting for the user input):

After the user has input something the line is cleared and another line is printed out

You've just entered the number 4

How can I achieve this in c ?

Upvotes: 0

Views: 726

Answers (1)

Yun
Yun

Reputation: 3837

Clearing any line is not possible in C. For this level of control in the terminal, you'd need to use a library like ncurses.

The closest you can get in pure C is by first printing the carriage return caracter (\r) and then printing over the previously printed text. You could print spaces to "clear" the text. However:

  • There is no method to find the length of that line, therefore this is not a good general solution.
  • Input functions such as scanf and getchar wait for a newline to appear ("the user pressed enter") before returning. The terminal will echo this newline and move to the next line, making it impossible to print over the line before it. There are ways to tell the terminal to not echo characters (e.g. for entering passwords), but these methods are OS-dependent and not part of C as was asked. Besides that, it would be a hacky way to get the intended result.

Upvotes: 1

Related Questions