gpt4 book ai didi

rust - 在循环中使用read_line时出现奇怪的行为

转载 作者:行者123 更新时间:2023-12-03 11:48:49 25 4
gpt4 key购买 nike

我在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

最佳答案

documentation for read_line :

Read all bytes until a newline (the 0xA byte) is reached, and append them to the provided buffer.



(强调一下。)您需要在读取下一行之前清除字符串,例如,通过在字符串上调用 clear() 方法,否则答案将累积在变量中。

或者,您可以在循环中定义变量(但是效率稍低,因为这种方式 String将无法为下一个答案重用已分配的存储,因此必须重新分配并重新分配)。

另请参见 this question,最近问过。看起来这是一个常见的陷阱。

关于rust - 在循环中使用read_line时出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61963885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com