Answer to Question #192787 in C++ for Shob

Question #192787

Let us consider a guessing game in which the computer picks a random twodigit number in the range from 0 to 99 and asks the user to guess the number. After each guess, the computer lets the player know how many digits of guessed numbers match the correct number. If the guessed number matches the correct number, the computer lets the player know the number of guesses the player made. 

Question1:Each function should be tested as soon as it is written. To do that, write the introduction and write the main() function and call the intro function.

Question2: To test the digitMatches() function, just call only that function with different inputs by giving two numbers. The function must work for any number in the range from 0 to 99.

Question3: You test the getInt() for non-numeric input first and then the guessNumber() function for the value of the number in the correct range.


1
Expert's answer
2021-05-19T06:05:27-0400
#include <iostream>
#include <random>
#include <ctime>
#include <string>


using namespace std;


void Menu();
int DigitMatches(int player, int comp);
bool GuessNumber(int player);
int GetInt();


int main()
{
	Menu();
	srand(time(0));
	int comp = rand() % 100;
	int player = 0;
	while (true)
	{
		cout << "Enter a number: ";
		player = GetInt();
		if (player == -1)
		{
			cout << "Wrong input format." << endl;
			continue;
		}


		if (!GuessNumber(player)) continue;
		if (player == comp)
		{
			cout << "You won! "<< player << " it is correct number!" << endl;
			break;
		}
		cout << "Number of number matches is: " << DigitMatches(player, comp) << endl;
	}
	return 0;
}


void Menu()
{
	cout << "Welcome to game, your task - guess the number which was generated by computer (0-99)" << endl;
	cout << "Let's play. Have fun" << endl;
}


int DigitMatches(int player, int comp)
{
	int dc1, dc2;
	if (comp < 10)	dc1 = dc2 = comp;
	else
	{
		dc1 = comp / 10;
		dc2 = comp % 10;
	}


	int dp1, dp2;
	if (player < 10) dp1 = dp2 = player;
	else
	{
		dp1 = player / 10;
		dp2 = player % 10;
	}
	if (comp < 10)
	{
		if (dc1 == dp1 || dc1 == dp2) return 1;
		else return 0;
	}
	else
	{
		if ((dc1 == dp1 && dc2 == dp2) || (dc1 == dp2 && dc2 == dp1)) return 2;
		if (dc1 == dp1 || dc1 == dp2 || dc2 == dp1 || dc2 == dp2) return 1;
	}
	return 0;
}


bool GuessNumber(int player)
{
	if (player > 99 || player < 1)
	{
		cout << "Please enter number in range 1-99!" << endl;
		return false;
	}
	else return true;
}


int GetInt()
{
	char ch;
	string str;
	while (true)
	{
		cin.get(ch);
		if (ch == '\n') break;
		if (isdigit(ch))
		{
			str += ch;
			continue;
		}
		else
		{
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			return -1;
		}
	}
	return stoi(str);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment