bulls and cows number guessing game

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 5 Exercise 12
Using std_lib_facilities.h by Bjarne Stroustrup.

[code language=”cpp”]
// Philipp Siedler
// Bjarne Stroustrup’s PP
// Chapter 5 Exercise 12

//input: 4621
//input: 4567
//input: 1234

#include "std_lib_facilities.h"

int main()
try
{
int guess;
int bulls = 0;
int cows = 0;

vector<int> guessVec;
vector<int> numToBeguessed{ 1,2,3,4 };

cout << "Enter 4 different digit number each ranging from 0 to 9 (for example 4567):\n";
while (bulls != 4) {
bulls = 0;
cows = 0;
if (cin >> guess) {
if (guess / 1000 >= 1 && guess / 1000 < 10) {

guessVec.push_back(guess / 1000 % 10);
guessVec.push_back(guess / 100 % 10);
guessVec.push_back(guess / 10 % 10);
guessVec.push_back(guess / 1 % 10);

for (int i = 0; i < guessVec.size()-1; i++) {
if (guessVec[i] == guessVec[i + 1]){
error("Enter 4 different numbers.");
}
}

for (int i = 0; i < guessVec.size(); i++) {
for (int j = 0; j < guessVec.size(); j++) {
if (numToBeguessed[j] == guessVec[i] && i == j) {
bulls++;
}
else if (numToBeguessed[j] == guessVec[i]) {
cows++;
}
}
}
}
else {
error("Enter a 4 digit number.");
}
}
else {
error("Enter a number.");
}

cout << "Bulls: " << bulls << " Cows: " << cows << "\n";
guessVec.clear();
}

cout << "You win!\n";
keep_window_open(".");
}

catch (runtime_error e) {
cout << e.what() << "\n";
keep_window_open(".");
}
catch (…) {
cout << "Extiting" << "\n";
keep_window_open(".");
}
[/code]
Enter 4 different digit number each ranging from 0 to 9 (for example 4567):
4621
Bulls: 0 Cows: 3
4567
Bulls: 0 Cows: 1
3120
Bulls: 0 Cows: 3
1234
Bulls: 4 Cows: 0
You win!
Please enter . to exit

Leave a Reply