0

I am new to rust and was following a rust lang book to build a guessing game but I noticed after running the below program doesn't print anything to console when I use print! but it prints when I use println!. Below is the code snippet:

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    let number = rand::thread_rng().gen_range(1..=100);

    loop {
        let mut input = String::from(" ");
        io::stdin().read_line(&mut input).expect("failed to read");

        let input_number: u32 = input.trim().parse().expect("Not a number");

        let message = match number.cmp(&input_number) {
            Ordering::Equal => "equal",
            Ordering::Less => "less",
            Ordering::Greater => "bigg",
        };

        print!("message: {}", message);
        // println!("message: {}", message);

    }
}

Can someone help me understand the odd behaviour?

OV3RKILL
  • 25
  • 8
  • 2
    Answered here, [How do I print output without a trailing newline in Rust?](https://stackoverflow.com/questions/37531903/how-do-i-print-output-without-a-trailing-newline-in-rust). `print!` doesn't "flush" the buffer of text, while `println!` does, so you need to manually flush it – Samathingamajig Jul 06 '23 at 16:25
  • `print!` doesn't append a newline to the message, and messages that don't end in newlines will not automatically flush stdio buffer. – Ivan C Jul 06 '23 at 16:25
  • 1
    Yes, io::stdout().flush() worked, thanks :) – OV3RKILL Jul 06 '23 at 16:32

1 Answers1

2

The file stdout (used by print and println) is likely line-buffered, meaning text is only flushed to the screen when a newline is encountered.

println automatically appends a newline, print doesn't, so you have to do it yourself.

Try appending the newline character (\n) to the string:

print!("message: {}\n", message);

Or print to the unbuffered stderr file using eprint:

eprint!("message: {}", message);

Do note that a newline is still not printed in the last example.