0

Lottery simulator c++

I have a lottery simulator that needs to have a random number vector as the lottery and a vector that allows user to enter 5 digits and compare the two arrays. If both vectors match it should print you win else you didn't win, all while comparing elements to see which match. My code does this, but it prints you lose after every random element as well as if the numbers match on each element. Could someone explain how I could get it to print if you win or lose after the random number vector as well as, the number of elements that match after the random number vector prints. Any advice is greatly appreciated. #include <iostream> #include <vector> #include <ctime> #include <cstdlib> using namespace std; const int size = 5; int main() { srand(time(NULL)); vector<int>lottery; vector<int>user; int guess; int count = 0; cout << " Make 5 guesses: "; for(int j = 1; j<=5; j++) { cin >> guess; } for(int i = 1; i<=5; i++) { lottery.push_back(rand() % 9 + 1); } for(int n : lottery) { if(n == guess) { count++; } user.push_back(guess); cout <<endl; if ( lottery == user) { cout << "Grand prize winner"; } else{ cout << "You didn't win, better luck next time" << endl; } cout << n << " " <<endl; cout <<"Number you got right: "<< count<< endl; } return 0; }

9th Dec 2018, 1:03 AM
dominic smith
dominic smith - avatar
4 Réponses
+ 3
There were a few things in your code I corrected: First of all, when taking input, you only got 'guess' five times, but didn't push those into 'user', so only the last entered value was saved. And second, you had everything following for (int n : lottery) inside the loop, which is why you got everything printed five times. 'lottery' was never the same as 'user' because you filled it with five values before the comparison, but you filled 'user' during the loop, meaning it had the wrong size to begin with + in the end, it contained five times 'guess'. Here is a refactored version: https://code.sololearn.com/cijJr5F3Hbds/?ref=app
9th Dec 2018, 9:15 AM
Shadow
Shadow - avatar
+ 2
Shadow, thank you very much. For some reason I mix up arrays and vectors and forget where they are the same. I'm getting better, but I clearly have a lot to learn.
9th Dec 2018, 10:31 PM
dominic smith
dominic smith - avatar
9th Dec 2018, 5:52 AM
Otumian Empire
Otumian Empire - avatar
+ 1
Otumain Empire, thanks for the examples, I am learning python, which is what I think the code you are using, c++ vectors aren't like anything I've learned in python so I wasn't able to apply those to this assignment.
9th Dec 2018, 10:35 PM
dominic smith
dominic smith - avatar