PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 18, 2022

[FIXED] How do I prevent characters from the previous line from appearing when overwriting it in Rust?

 September 18, 2022     printing, rust, stdout     No comments   

Issue

I have the following code which enables me to make console output appear on the same line. However, if a value that was previously printed was of greater length than values after it, the remnants of the longer value will show up. I have seen other questions about the same thing in languages like Python, but I'm not sure how to overcome this in Rust.

Here's an example:

use std::io::prelude::*;

fn main() {
    let fruits = ["Blueberry", "Orange", "Cherry", "Lemon", "Apple"];
    print_value(&fruits);
}

fn print_value(e: &[&str]) {
    for val in e {
        print!("\rStatus: {}", val);
        std::io::stdout().flush().unwrap();
        // pause program temporarily
        std::thread::sleep(std::time::Duration::new(2, 0));
    }
}

Solution

Some terminals have a special character sequence that, when printed, clears the line to the right of the current cursor position.

VT100-compatible terminals have a character sequence EL0 for that. In Rust it can be expressed with "\x1B[K".

Here's a little thingy that might prove an example.

To do that in a more portable way you use a terminal library, such as term and it's delete_line method.



Answered By - ArtemGr
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing