Why print!() is printing after read()?

use std::io;

fn main() {
    println!("Convert Fahrenheit and Celsius");

    loop {
        print!("Type the temp ");

        let num: f64 = match read().trim().parse() {
            Ok(t) => t,
            Err(_) => break,
        };

        println!("Is the temperature entered in Fahrenheit or Celsius? Type C or F");
        match read().trim().parse() {
            Ok('C') => cel_to_fah(num),
            Ok('F') => fah_to_cel(num),
            _ => break,
        };
    }
}

fn read() -> String {
    let mut line = String::new();
    io::stdin()
        .read_line(&mut line)
        .expect("Failed to read a line");
    line
}

fn cel_to_fah(t: f64) {
    println!("cel to fah {t}");
}
fn fah_to_cel(t: f64) {
    println!("fah to cel {t}");
}

output:

Convert Fahrenheit and Celsius
12
Type the temp Is the temperature entered in Fahrenheit or Celsius? Type C or F

I'm reading the book of rust, and I was trying to solve the 'convert fah and cel', but something very strange is happening, or did I something wrong?

Can someone explain to me why the print!() macro looks like is executing after the read function?

And my English is horrible.

I guess it's a buffer problem, either use println!() instead, or try add std::io::stdout().flush().unwrap(); after the print!() statement.

btw, please paste the code and format it properly, screenshots may be hard to read on some devices.

2 Likes

wow, that's strange, I just added a '\n' in the end of str of print!() and worked. thanks.

by default, writes to stdout is bufferred, until being flushed implicitly when the buffer is full, or a new line is printed, or explicitly flushed by calling the flush() function.

you observe similar behavior in C/C++, e.g. see std::endl in C++:

1 Like