The coding below is the game of Bulls and Cows Please change the coding below wi
ID: 3716392 • Letter: T
Question
The coding below is the game of Bulls and Cows
Please change the coding below with using printf and scanf_s
Also, Please make a function and a struct out of the coding.
Thank you.
------------------------------------------------------------------
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void main()
{
int save[3];// Random number generating
int input[3];// User input number
int i, j;// for loop
int st;// strike
int b;// ball
srand((unsigned)time(NULL));
cout << "Start" << endl;
for (i = 0, j = 0; i < 3; i += (i == j))
{
save[i] = rand() % 10;
for (j = 0; j < i && save[i] != save[j]; j++);
}
while (1)
{
while (1)
{
cout << " Enter 3 numbers <<" << endl;
cin >> input[0] >> input[1] >> input[2];
if ((input[0] < 0) || (input[0] > 9) || (input[1] < 0) || (input[1] > 9) || (input[2] < 0) || (input[2] > 9))
{
cout << "Invalid!" << endl << endl;
}
else if ((input[0] == input[1]) || (input[0] == input[2]) || (input[1] == input[2]))
{
cout << "Invalid!" << endl << endl;
}
else break;
}
st = 0;
b = 0;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
if (save[i] == input[j])
{
if (i == j)
{
st++;
}
else
{
b++;
}
input[j] = 100;
}
}
}
cout << st << " Strike " << b << " Ball" << endl;
if (st == 3) break;
}
cout << "End" << endl;
}
Explanation / Answer
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
struct game{
int save[3];// Random number generating
int input[3];// User input number
int st;// strike
int b;// ball
};
void fxn( struct game);
int main()
{
int i, j;// for loop
struct game ob;
srand((unsigned)time(NULL));
printf("Start ");
for (i = 0, j = 0; i < 3; i += (i == j))
{
ob.save[i] = rand() % 10;
for (j = 0; j < i && ob.save[i] != ob.save[j]; j++);
}
fxn(ob);
printf("End ");
}
void fxn( struct game ob)
{
int i, j;
while (1)
{
while (1)
{
printf(" Enter 3 numbers << ");
scanf("%d%d%d", &ob.input[0] , &ob.input[1] , &ob.input[2]);
if ((ob.input[0] < 0) || (ob.input[0] > 9) || (ob.input[1] < 0) || (ob.input[1] > 9) || (ob.input[2] < 0) || (ob.input[2] > 9))
{
printf("Invalid! ");
}
else if ((ob.input[0] == ob.input[1]) || (ob.input[0] == ob.input[2]) || (ob.input[1] == ob.input[2]))
{
printf("Invalid! ");
}
else break;
}
ob.st = 0;
ob.b = 0;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
if (ob.save[i] == ob.input[j])
{
if (i == j)
{
ob.st++;
}
else
{
ob.b++;
}
ob.input[j] = 100;
}
}
}
printf("%d Strike %d Ball", ob.st, ob.b);
if (ob.st == 3) break;
}
}