`print!()` 在 Rust 中在循环内使用时不打印消息。

huangapple go评论70阅读模式
英文:

print!() doesn't print the message when used inside a loop in rust

问题

我是Rust的新手,正在跟随一本Rust语言书籍来构建一个猜数字游戏,但我注意到在运行下面的程序后,当我使用print!时,它没有在控制台上打印任何内容,但当我使用println!时,它可以打印出来。

以下是代码片段:

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);
    }
}

有人能帮我理解这种奇怪的行为吗?

英文:

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?

答案1

得分: 2

The file stdout(由printprintln使用)可能是行缓冲的,这意味着只有在遇到换行时才会将文本刷新到屏幕上。

println会自动附加换行符,print不会,所以你需要自己添加。

尝试将换行字符(\n)附加到字符串上:

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

或者使用eprint打印到不带缓冲的stderr文件:

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

请注意,最后一个示例仍然不会打印换行符。

英文:

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.

huangapple
  • 本文由 发表于 2023年7月7日 00:23:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76630819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定