#include #include using namespace std; int count_correct(string& secret, string const& guess) { int count = 0; for (unsigned int i = 0; i < secret.size(); ++i) { if (secret.at(i) == guess.at(i)) { secret.at(i) = ' '; // do not count again! ++count; } } return count; } int count_existing(string& secret, string const& guess) { int count = 0; for (unsigned int i = 0; i < guess.size(); ++i) { unsigned int pos = secret.find( guess.at(i) ); if ( pos != string::npos ) { secret.at(pos) = ' '; // do not count again! ++count; } } return count; } int main() { random_device rdev; uniform_int_distribution dist(1000, 9999); const string secret = to_string(dist(rdev)); string guess; int round = 0; cout << secret << endl; cout << "A secret number is generated, enter your guesses: " << endl; do { ++round; cin >> guess; cin.ignore(1000, '\n'); if (guess.size() != 4) { cerr << " ERROR: Your guess should be 4 digits!" << endl; } else { string scopy = secret; int correct = count_correct(scopy, guess); int wrong_place = count_existing(scopy, guess); cout << " " << correct << " correct and " << wrong_place << " in wrong place!" << endl; } } while (guess != secret); cout << "Correct! You won in " << round << " rounds!" << endl; return 0; }