Why is the output with print! different from with println!, followed by an endless loop?

// The output with println! is from 1 to 499.

fn main() {
    let mut i = 1;
    while i <= 1000 {
        if i == 500 { continue; }
        println!("{}", i); 
        i += 1;
    }
}

// The output with print! is from 1 to 283.

fn main() {
    let mut i = 1;
    while i <= 1000 {
        if i == 500 { continue; }
        print!("{} ", i); 
        i += 1;
    }
}

Stdout handle uses buffered output, currently using std::io::LineWriter which flushes the buffer whenever a newline is detected. println! prints a newline, print! as used here doesn't.

It's possible to manually force STDOUT to be flushed by calling stdout's flush method.

use std::io::{stdout, Write};

fn main() {
    let mut i = 1;
    while i <= 1000 {
        if i == 500 { continue; }
        print!("{} ", i);
        stdout().flush().unwrap();
        i += 1;
    }
}
1 Like

Thanks!
Besides detecting a newline, std::io::LineWriter also flushes the buffer whenever output exceeds 1024 bytes, is it right?

You may also consider moving the flush to the termination condition:

if i == 500 {
    stdout().flush().unwrap();
    loop {}
}
1 Like
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.