gpt4 book ai didi

for-loop - Rust 正在跳过 for 循环

转载 作者:行者123 更新时间:2023-12-03 11:45:09 24 4
gpt4 key购买 nike

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

1年前关闭。




Improve this question




我对 rust 很陌生,只是想制作一个刽子手游戏来帮助我学习语言。我做了一个 for 循环来检查我输入的字符是否在我猜到的所有过去字符的向量中。但是当运行它时,它只是不断地再次询问该字母,在通过调试器之后它会完全跳过 for 循环。
我正在使用带有 lldb 的 vscode 进行调试。
任何人都可以伸出援助之手向我解释或帮助我弄清楚为什么它不起作用。

use rand::random;

fn take_input(pre_guessed: &mut std::vec::Vec<char>) -> char{
let mut run = true;

print!("Enter letter: ");
let mut temp_guess = String::new();
let guess_char = match std::io::stdin().read_line(&mut temp_guess){
Ok(_) => temp_guess.chars().next().expect("Could not convert guess to char"),
Err(_) => '>'
};
println!();

for i in pre_guessed.iter(){ // THIS IS THE FOR LOOP THAT IS SKIPPED OVER
if *i == guess_char{
run = false;
}
}

if run == false{
pre_guessed.push(guess_char);
guess_char
} else {
take_input(pre_guessed)
}

}

fn get_word() -> String {
// goes to a text file and gets a word
}

fn check_correct(guessed_vec: &std::vec::Vec<char>) -> bool{
let mut complete = true;
for i in guessed_vec.iter(){
if *i == '-'{
complete = false;
}
}

complete

}

fn main() {
let word_to_guess = get_word();
println!("{}", word_to_guess);
let mut encoded_word = vec!['-'; word_to_guess.len()];

let mut guessed = false;

let mut guessed_letters: std::vec::Vec<char> = Vec::new();
let mut wrong_letters: std::vec::Vec<char> = Vec::new();

while guessed == false{
println!("Guessed letters: {:?}", wrong_letters);
for i in encoded_word.iter(){
print!("{}", i);
}
println!();

let guess = take_input(&mut guessed_letters);
let mut temp_count = 0;
let mut temp_match = false;
for i in word_to_guess.chars(){
if guess == i{
encoded_word[temp_count] = i;
temp_match = true
}
temp_count += 1;
}

if temp_match == false{
wrong_letters.push(guess);
}

guessed = check_correct(&guessed_letters)
}

}

最佳答案

  • guessed_letters开始为空。
  • 唯一增加它的是pre_guessed.push(guess_char)run == false .
  • run开始 true .
  • 唯一将它设置为 false是什么时候*i == guess_char对于任何元素ipre_guessed (即 guessed_letters )。
  • guessed_letters只能在 run 时变为非空为假, run只能在 guessed_letters 时变为假是非空的。
    看起来你的意思是:
    if run {  // no == false
    pre_guessed.push(guess_char);
    guess_char
    } else {
    take_input(pre_guessed)
    }

    关于for-loop - Rust 正在跳过 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62995612/

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