#include <iostream>
constint MAX_GUESSES = 10;
bool checkGuess(char guesses[], char guess)
{
// for info, static ensures that count
// retains its value when we leave the
// function.. normally each time we call
// the function it would be set to 0.
staticint count = 0;
// loop through the array to see if
// whatever is in guess is already
// there.. return true if it is.
for (int i = 0; i < MAX_GUESSES; i++)
if (guesses[i] == guess)
returntrue;
// not there so store it and return false
guesses[count] = guess;
count++;
returnfalse;
}
int main()
{
// storage for my guesses, and guess
char myGuessList[MAX_GUESSES] = { 0 };
char guess;
for (int i = 0; i < MAX_GUESSES; i++)
{
// grab guess
std::cout << "Enter Guess: ";
std::cin >> guess;
// check quess.
if (checkGuess(myGuessList, guess))
std::cout << "You tried " << guess << "!" << std::endl;
{
// it wasnt already there so do something with it..
}
}
return 0;
}
Enter Guess: A
Enter Guess: B
Enter Guess: C
Enter Guess: A
You tried A!
I would probably follow the same kind of approach, but use a more generic function than Softrix's checkGuess(), e.g.
1 2 3 4 5 6 7 8 9
// generic search function -- can be used elsewhere
// adjust type to suit
int findInArray(int arr[], int size, int val) {
for (int i = 0; i < size; i++) {
if (arr[i] == val)
return i;
}
return -1; // means not found by convention
}
then, where myGuessList is an array, MAX_GUESSES is the size of the array, and guess is a variable set to the value of the latest guess, ...
1 2 3 4 5 6 7 8 9
if (-1 == findInArray(myGuessList, MAX_GUESSES, guess))
{
// it not found in list...
// TODO implementation
}
else
{
std::cout << "You've already tried " << guess << "!\n";
}
Note that you should aim to avoid global (aside from common consts) and static variables if at all possible!!
Andy
PS I assume you're writing your guessing game to learn C++, so the suggested solutions are the kind of thing you should go for.
But if you were wanting to write your game as succintly as possible then you'd use the standard C++ containers and algorithms. If you don't care what order the user guessed the numbers in, the best bet would probably be std::set. http://www.cplusplus.com/reference/set/set/