gpt4 book ai didi

rust - Rust 教科书的猜谜游戏扩展显示出奇怪的行为

转载 作者:行者123 更新时间:2023-11-29 08:26:46 25 4
gpt4 key购买 nike

所以我将猜谜游戏扩展为基本上询问用户是否想再玩一次。如果他们键入 y,程序将返回到主游戏循环,如果他们键入 n,程序将跳出当前循环并结束。如果他们输入任何其他内容,理论上它应该直接跳到 play_again 循环的顶部并将 yae_or_nay 变量重新分配为玩家接下来输入的任何内容。但它并没有这样做,或者至少看起来它错误地覆盖了它。我是否错误地重新分配了变量?这是代码(请注意,程序的前半部分与教科书上的几乎相同,但由于程序太短,我决定包含整个程序):

extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng; // random number generation library from rand

fn main() {
println!("Guessing game!\n");

let mut answer = rand::thread_rng().gen_range(1,101);
'gameloop: loop {
println!("Please print your guess:");

let mut yae_or_nay = String::new();
let mut guess = String::new();

io::stdin().read_line(&mut guess)
.expect("Failed to read line");

let guess : u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Not a number!");
continue;
}
};

match guess.cmp(&answer) {
Ordering::Less => println!("Higher!"),
Ordering::Greater => println!("Lower!"),
Ordering::Equal => {
println!("Correct! Would you like to play again? (y/n)");
'play_again: loop {
io::stdin().read_line(&mut yae_or_nay)
.expect("Failed to read line.");

match yae_or_nay.trim() { // match against a string
"y" => {
answer = rand::thread_rng().gen_range(1,101);
println!("Playing again...");
continue 'gameloop;
},
"n" => {
println!("Thanks for playing! Exiting now.");
break
},
_ => {
println!("what? You entered {}", &yae_or_nay);
continue 'play_again
}
};
}
}
}
}
}

这是控制台输出的一个片段:

46
Correct! Would you like to play again? (y/n)
i
what? You entered i

y
what? You entered i
y

n
what? You entered i
y
n

. // period here for formatting sake, not actually in console

如您所见,我的程序重新分配 yae_or_nay 的方式似乎很奇怪。有人知道发生了什么事吗?在此先感谢您的帮助。

最佳答案

问题是您永远不会清除 yae_or_nayio::stdin().read_line(&mut yae_or_nay)append到字符串,而不是替换它的内容。

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

要么你应该做

yae_or_nay.clear();

在您阅读它之前,或者可能更好的做法是将声明移至

'play_again: loop {
let mut yae_or_nay = String::new();
io::stdin().read_line(&mut yae_or_nay)
.expect("Failed to read line.");

关于rust - Rust 教科书的猜谜游戏扩展显示出奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53182656/

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