Hangman游戏字符串填充问题:猜中字符无法全部显示
解决Hangman游戏中猜中字母无法全部替换的问题
嗨,我知道你卡在哪了!问题出在你获取字符索引的方式上——你用std::string::find(&character)来找当前字符的位置,但find默认只会返回第一个匹配字符的索引。这就导致循环到后面的'a'时,每次都只会修改第一个'-'的位置,而不是它们自己对应的位置,所以最后两个'a'始终没被替换。
举个例子,你的目标字符串是"ataamataesaa",当循环到第3个、第4个,还有末尾的两个'a'时,find(&character)每次都返回0(第一个'a'的索引),这些位置的'-'根本没被触及到。
给你两种简单的修正方案:
方案一:使用带索引的for循环
直接通过索引遍历字符串,这样能精准定位每个字符的位置:
std::string word_to_guess = "ataamataesaa"; std::string word_to_fill(word_to_guess.length(), '-'); char user_guess = 'a'; for (std::size_t i = 0; i < word_to_guess.length(); ++i) { if (word_to_guess[i] == user_guess) { word_to_fill[i] = user_guess; } } std::cout << word_to_fill;
方案二:范围循环+手动跟踪索引
如果你更习惯用范围循环,可以额外加一个变量来记录当前索引:
std::string word_to_guess = "ataamataesaa"; std::string word_to_fill(word_to_guess.length(), '-'); char user_guess = 'a'; std::size_t current_index = 0; for (auto character : word_to_guess) { if (character == user_guess) { word_to_fill[current_index] = user_guess; } current_index++; } std::cout << word_to_fill;
这两种方式都能把所有匹配的'a'正确替换到对应的位置,你运行一下就会看到最后两个'a'正常显示啦!
内容的提问来源于stack exchange,提问作者user11281685
相关产品推荐
相关产品推荐

