1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
void generate_actual(int actual[], int SIZE)
{
for (int i=0; i < SIZE; ++i)
actual[i] = std::rand() % 9 + 1;
}
bool read_guess(int guess[], int SIZE)
{
char buffer[256];
char *token;
std::cin.getline(buffer, sizeof buffer);
token = std::strtok(buffer, " ");
for (int i=0; i < SIZE; ++i)
{
if (token == NULL)
{
std::cerr << "Not enough numbers were given.\n";
return false;
}
int temp = std::strtol(token, NULL, 10);
if (temp < 1 || temp > 9)
{
std::cerr << "Given numbers must be between 1 and 9.\n";
return false;
}
guess[i] = temp;
token = std::strtok(NULL, " ");
}
return true;
}
bool can_find(int n, int actual[], int SIZE)
{
for (int i=0; i < SIZE; ++i)
if (n == actual[i])
return true;
return false;
}
void show_similarity(int guess[], int actual[], int SIZE)
{
for (int i=0; i < SIZE; ++i)
if (guess[i] == actual[i])
std::cout << "A ";
else
if (can_find(guess[i], actual, SIZE))
std::cout << "C ";
else
std::cout << "- ";
std::cout << '\n';
}
bool are_the_same(int guess[], int actual[], int SIZE)
{
for (int i=0; i < SIZE; ++i)
if (guess[i] != actual[i])
return false;
return true;
}
int main()
{
const int SIZE = 5;
int actual[SIZE]; // will store the randomly generated numbers
int guess[SIZE]; // will store the user's temporary guessed numbers
std::srand(std::time(NULL)); // seed the random number generator
// this function will fill the `actual' array with random numbers, 1-9
generate_actual(actual, SIZE);
std::cout << "Input a sequence of " << SIZE << " numbers from 1 to 9:\n";
while (true)
{
// this function will read user input into the `guess' array
if (!read_guess(guess, SIZE))
{
std::cerr << "Let's try this again...\n";
continue;
}
// this function will print the appropriate "A C A - -" kind of code
show_similarity(guess, actual, SIZE);
if (are_the_same(guess, actual, SIZE))
{
std::cout << "Congratulations, you have won!\n";
break;
}
else
std::cout << "Try again!\n\n";
}
std::system("PAUSE"); // you may not need this line
}
|