我在Rust中的第一个程序应该以C或F字符的形式从用户那里获取输入:
use std::io;
fn main() {
let mut srcunit = String::new();
let mut switch = true;
while switch {
println!("source unit? F or C?");
io::stdin().read_line(&mut srcunit).expect(
"failed to read src unit",
);
if srcunit.trim() == "F" || srcunit.trim() == "C" {
println!("doing things right with {}", srcunit);
switch = false;
} else {
println!("either F or C, not {}", srcunit);
}
}
println!("you pressed {}", srcunit);
}
当我启动程序并按下F或C时,它工作正常,所以我跳过这里.当我按下另一个角色时,奇怪的部分出现了.我希望我的程序再次请求F或C,直到我按下其中一个字符.当我这样做时,它应该离开while循环,告诉我按下了什么.
source unit? F or C?
G
either F or C, not G //so far so good
source unit? F or C?
F
either F or C, not G //why is F not assigned to the srcunit variable? It's supposed to leave the loop now.
F //why does it print this line? I didn't press a key or have a println function/macro that does this
source unit? F or C?
V
either F or C, not G //it's still G, wtf
F //again, why are those two lines printed? Where does it store, that I pressed F previously?
V