英文:
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(由print和println使用)可能是行缓冲的,这意味着只有在遇到换行时才会将文本刷新到屏幕上。
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论