I'm not a beginner programmer as I have experience in Node and Ruby, but I'm a beginner when it comes to C++. And as C++ is quite different from these two, I figured I could use any tips, tricks, hints and pointers (hah!) to learn how to actually write C++ and to get the most out of the language. I feel a bit like I'm trying to write JS but in C++ syntax.
To get me started I've written a Bulls and cows game which works as I intended it to, but like I said above, I need help in improving the code generally as well as actually utilizing the built in C++ methods.
I'm wondering if it's worthwhile to write a separate function for say the random number generation, or would that be a waste of memory?
I've also seen that many in the C++ community seem to favour comments instead of descriptive variable/function names. Example:
int a = 3.14159265359; // pi with 11 decimal numbers
instead of:
int pi_eleven_decimals = 3.14159265359;
Is that merely a question of taste or is it simply how it's done in C++?
The bulls and cows game code:
#include "pch.h"
#include <iostream>
#include <time.h>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main() {
int bull;
int cow;
int find_count;
int value1;
int value2;
int value3;
int value4;
int calculate_cows;
string secret_number = "";
string guess = "";
bool run_game = true;
char again;
bool win;
cout << "Welcome to the Bulls and Cows game!" << endl;
while (run_game == true) {
bull = 0;
cow = 0;
find_count = 0;
calculate_cows = 0;
//random number generation begin
srand(time(NULL));
value1 = rand() % 10;
value2 = rand() % 10;
value3 = rand() % 10;
value4 = rand() % 10;
// random number generation stop
stringstream ss;
ss << value1 << value2 << value3 << value4;
secret_number = ss.str();
win = false;
while (win == false) {
cout << "Make a guess: (XXXX)" << endl;
cin >> guess;
for (int i = 0; i < secret_number.length(); i++) {
if (guess.at(i) == secret_number.at(i)) {
bull++;
}
}
for (int i = 0; i < guess.length(); i++) {
int secret = secret_number.at(i);
if (guess.find(secret)) {
find_count++;
}
}
calculate_cows = find_count - bull;
cow = (calculate_cows < 0) ? 0 : calculate_cows;
cout << "Bulls: " << bull << endl << "Cows: " << cow << endl;
if (bull == 4) {
cout << "You win!" << endl;
win = true;
}
else {
bull = 0;
cow = 0;
find_count = 0;
}
}
cout << "Play again? (y/n)" << endl;
cin >> again;
run_game = (again == 'y') ? true : false;
}
cout << "Thanks for playing! :)" << endl;
return 0;
}
'pch.h'
? \$\endgroup\$pi
anint
? \$\endgroup\$pch.h
is precompiled header and not really required here. You can safely delete it \$\endgroup\$