Kameron
Kameron

Reputation: 13

Trying to compare two character arrays

void program() {
  int x;
  bool playAgain = true;
  const int Maxword = 5;
  char Guess[Maxword]{};
  std::string words[Maxword] = {"Hello", "World", "Shift", "Green", "Seven"};
  srand(time(NULL));
  int iSecret = rand() % Maxword;
  std::string Word(words[iSecret]);
  for (int i = 0; i < 5; i++) {
    std::cout << Word[i] << std::endl;
  }
  while (playAgain == true && Guess != Word) {
    for (int i = 0; i < 5; i++) {
      std::cout << ("Please enter the letters you would like to guess")
                << std::endl;
      std::cin >> Guess[i];
      std::cout << Guess[i] << std::endl;
      cout << "This is Guess " << Guess;
      cout << "This is the Word " << Word;
    }
    for (int i = 0; i < 5; i++) {
      if (Guess[i] == Word[i]) {
        std::cout << Guess[i] << "\t"
                  << "Is in the right place" << std::endl;

      } else if (Guess[i] != Word[i]) {
        std::cout << Guess[i] << "\t"
                  << "Isnt in the right place" << std::endl;
      } else {
      }
    }
  }
}

So this is my code for my program and I want the while loop to be broken out of once The user guesses the correct word however even if I type in the correct word it keeps looping back How would I make them compare one another then break out. Why in the picture after I print out the array guess these weird symbols there.enter image description here

I fixed the code a little to give a better view but in the Guess array there are all these random characters so they will never be the same.

Upvotes: 0

Views: 71

Answers (1)

Lev M.
Lev M.

Reputation: 6269

You never put a \0 (null character) terminator at the end of Guess so when you try to print the whole array like this:

cout << "This is Guess " << Guess;

The printing does not stop at the end of the array, and instead runs over the memory until your program crashes, or it finds a random \0 character.

The garbage you see are random memory values stored right after the end of the array.

Upvotes: 1

Related Questions