Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear the current line of stdout?

Tags:

rust

I'm trying to make a status indicator in Rust that prints to stdout. In other languages, I've used a function that clears the current line of stdout while leaving the others untouched. I can't seem to find a Rust equivalent. Is there one? Here's a small example of what I'm looking for

for i in 0..1000 {
    stdio::print(format!("{}", i).as_slice));
    stdio::clear();
}
like image 275
Lily Mara Avatar asked Mar 03 '15 03:03

Lily Mara


People also ask

How do you clear the print in Python?

system('cls') to clear the screen. The output window will print the given text first, then the program will sleep for 4 seconds and then screen will be cleared and program execution will be stopped.

How do I delete a line in command prompt?

As such: Press Ctrl + a to move the cursor to the beginning of the line and then Ctrl + k to delete to the end of line.


2 Answers

On an ANSI terminal (almost everything except Command Prompt on Windows), \r will return the cursor to the start of the current line, allowing you to write something else on top of it (new content or whitespace to erase what you have already written).

print!("\r")

There is nothing available in the standard library to do this in a platform-neutral manner.

like image 196
Chris Morgan Avatar answered Oct 27 '22 01:10

Chris Morgan


Utilizing the ASCII code for backspace is one option, for example:

print!("12345");
print!("{}", (8u8 as char));

This will end up outputting "1234" after the 5 is removed as a result of printing the backspace character (ascii code 8). Strangely, Rust does not recognize \b as a valid character escape.

like image 30
yarduddles Avatar answered Oct 27 '22 00:10

yarduddles