我需要输出_之间的空格

时间:2018-03-04 17:47:50

标签: c++

我或多或少完成了我的第一个C ++项目,它是一个Hangman游戏,到目前为止一切正常。唯一的问题是我需要在表示隐藏单词的下划线(_)之间有空格。如果有人能帮助我,我会非常感激。

// UNCOMMENT THE FOLLOWING LINE (REMOVE THE TWO SLASHES AT THE BEGINNING) TO RUN AUTOMATIC TESTS
#include "tests.h"

#include <iostream>
#include <string>
#include "hangman.h"

int main(){

    using namespace std;



    // display the hidden word
    std::string word_to_guess = chooseWord();
    int misses = 0;
    std::string displayed_word = word_to_guess;

    for(int i=0; i< displayed_word.length(); i++)
        displayed_word[i] = '_';

     int attempts = 6;    
      std::cout << "Attempts left:" << attempts << std::endl;
    std::cout << "[ " << displayed_word << " ]" << std::endl;  


    //check for correct letter

    while(1){
        std::cout << "Your guess";
        std::cout << ":";
        char guess;
        std::cin >> guess;

        bool Correct = false;
        for(int i=0; i< word_to_guess.length(); i++)
            if (guess == word_to_guess[i]) {
                displayed_word[i] = word_to_guess[i];
                Correct = true;
            }    

        if (!Correct)
            attempts--;
        if (!Correct)    
            std::cout << "Attempts left:" << attempts << std::endl;
        if (!Correct)    
            std::cout << "[ " << displayed_word << " ]" << std::endl; 


        if (Correct)    
                std::cout << "Attempts left:" << attempts << std::endl;
        if (Correct)        
             std::cout << "[ " << displayed_word << " ]" << std::endl; 


       //check for win or lose
      if (attempts==0) 
          std::cout << "The word was: " << word_to_guess << std::endl << "You lost!";
          if (attempts==0)
              return 0;

      if (!word_to_guess.find(displayed_word))
          std::cout << "You won!";
          if (!word_to_guess.find(displayed_word))
              return 0;
    }


}

1 个答案:

答案 0 :(得分:0)

首先,您可以简化此

if (!Correct)    
    std::cout << "Attempts left:" << attempts << std::endl;
if (!Correct)    
    std::cout << "[ " << displayed_word << " ]" << std::endl; 

if (Correct)    
    std::cout << "Attempts left:" << attempts << std::endl;
if (Correct)        
    std::cout << "[ " << displayed_word << " ]" << std::endl; 

由此

std::cout << "Attempts left:" << attempts << std::endl;
std::cout << "[ " << displayed_word << " ]" << std::endl; 

现在,关于你的问题,我认为最好的解决方案是替换

std::cout << "[ " << displayed_word << " ]" << std::endl;

由此

std::cout << "[";
for(int i = 0; i < displayed_word.length(); i++) {
    if(i == 0 || displayed_word[i] == '_')
        std::cout << " ";
    std::cout << displayed_word[i];
    if(i == displayed_word.length()-1 || (displayed_word[i] == '_' && displayed_word[i+1] != '_'))
        std::cout << " ";
}
std::cout << "]" << std::endl;

阐释:

我们在开头和结尾以及下划线周围放置空格,但我们确保在两个下划线之间只放置一个空格。