코딩Coding/Rust연습

Rust연습❤️Processing 0~100%올라가는 프린트 ㅎㅎ

내인생PLUS 2022. 8. 13. 23:23
728x90
use std::{
    io::{stdout, Write},
    thread::sleep,
    time::Duration,
};

fn main() {
    let mut stdout = stdout();

    for i in 0..=100 {
        print!("\rProcessing {}%...", i);
        // or
        // stdout.write(format!("\rProcessing {}%...", i).as_bytes()).unwrap();

        stdout.flush().unwrap();
        sleep(Duration::from_millis(20));
    }
    println!();
}

 

 

cargo run

   Compiling char v0.1.0 (/Users/globalyoung/Documents/test/rust/char)
    Finished dev [unoptimized + debuginfo] target(s) in 2.16s
     Running `target/debug/char`
     
Processing 100%...

 

 

https://stackoverflow.com/questions/59890270/how-do-i-overwrite-console-output

 

How do I overwrite console output?

Is there a way to overwrite console output using Rust instead of simply appending? An example would be printing progress as a percentage; I would rather overwrite the line than print a new line.

stackoverflow.com

 

 

 

 

 

 

30에서 부터 0으로 줄어듬

 

use crossterm::{cursor, terminal, ExecutableCommand, QueueableCommand};
use std::io::{stdout, Write};
use std::{thread, time};

fn main() {
    let mut stdout = stdout();

    stdout.execute(cursor::Hide).unwrap();
    for i in (1..30).rev() {
        stdout.queue(cursor::SavePosition).unwrap();
        stdout
            .write_all(format!("{}: FOOBAR ", i).as_bytes())
            .unwrap();
        stdout.queue(cursor::RestorePosition).unwrap();
        stdout.flush().unwrap();
        thread::sleep(time::Duration::from_millis(100));

        stdout.queue(cursor::RestorePosition).unwrap();
        stdout
            .queue(terminal::Clear(terminal::ClearType::FromCursorDown))
            .unwrap();
    }
    stdout.execute(cursor::Show).unwrap();

    println!("Done!");
}

 

 

Done!

 

 

 


 

반응형