I am doing a bulls and cows game. I need that if the code they have to guess has
ID: 3756887 • Letter: I
Question
I am doing a bulls and cows game. I need that if the code they have to guess has like 4 digits, and they put 3 digits, it say "You can only use 4 digits." and they ask to enter a number again. if they did enter the right amount of digits then it continues the loop of assigning how many bulls and cows they got. its not even outputting the "You need.." part. Hope to hear any feedback, thank you.
while(!won) {
int flag= 0;
while (flag!=1) {
// their guess and the bulls and cows
// getting their guess input and storing it
vector<int> UserGuess;
int UserInput=0;
cout << "Enter Guess: ";
cin >> UserInput;
int remainder= UserInput;
int index= digits;
// cout << UserInput << endl;
int cows=0;
int bulls=0;
// storing each number from guess which is stored backwards
while(index!= 0) {
remainder = UserInput % 10;
UserInput = UserInput / 10;
UserGuess.push_back(remainder);
index = index - 1;
}
vector<int> finalInput;
// reversing that stored guess
for(int i=UserGuess.size()-1; i >= 0; --i) {
finalInput.push_back(UserGuess.at(i));
}
// if finalinput size doesnt equal codetoguess then ask again , this is the part that i'm messing up on
if (finalInput.size() != codetoguess.size()) {
cout << "You can only use " << codetoguess.size() << " digits.";
flag= 0;
}
else {
flag =1;
}
// assigning cows and bulls
for(int i=0; i< codetoguess.size(); ++i) {
for (int j=0; j< finalInput.size(); ++j) {
if (codetoguess.at(i)== finalInput.at(j)) {
if (i == j) {
bulls++;
}
if(i != j){
cows++;
}
}
}
}
// if all bulls are guessed right , else output number of bulls and cows
if(bulls == digits){
won = true;
cout << bulls << " bulls... ";
for(int i = 0; i < digits; i++) {
if (i==0) {
cout << codetoguess.at(i);
}
else {
cout << "-" << codetoguess.at(i);
}
}
cout << " is correct!" << endl;
}
else {
cout << bulls << " bulls" << endl;
cout << cows << " cows" << endl;
}
}
}
return 0;
}
Explanation / Answer
I have studied your code.It's logic seems to be correct But you might me making errors in coding
Below,I am writing some points in which you might be facing the error -
1) In line -
int index = digits; You have not initialized "digits" variable
2) You have not shown how the "codetoguess" vector was initialized It might be faulty as well
3) In the if condition to check number of digits entered by user that is -
if (finalInput.size() != codetoguess.size()) ;
You should use continue statement after the statement flag = 0; so that the remaining code after this if-else part will not run
Hope i have answered your question satisfactorily.Leave doubts in comment section if any.
If you are still facing any issues with your code then i suggest you to post complete code in comment section so that i can help you in a better way
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.