Max Orozco - 7 months ago 71

C++ Question

I am having trouble getting my functions right for a program I am writing for a homework assignment. The assignment asks me to write a lottery simulation in which the user guesses 7 numbers between 1 and 40. the numbers are then compared to randomly generated numbers from a separate function. This function is meant to ask for and store the 7 numbers in an array:

`const int size = 7;`

int getLottoPicks(int userNum[size]) { //collects and stores the user input

for (int i = 0; i < size; i++) {

cout << "Please enter number " << i+1 << ": ";

cin >> userNum[i];

if (userNum[i] < 1 || userNum[i] > 40) { //keeps the number between 1 and 40

cout << "The number must between 1 and 40." << endl

<< "Please enter another number: ";

cin >> userNum[i];

}

}

return userNum[size];

}

Currently this function outputs something crazy like

What modifications do I have to make to get this to output a 7 number array when called?

Also, what would be the best way to find and prevent duplicate values from being input by the user?

Thanks in advance.

Answer

Your function doesn't output anything other than the prompt. And it returns an element one-past the end of your array. You have undefined behavior going on here.

I'd suggest you don't need to return anything, since your function already inserts into the array it was given. Now to fix it, you can do the following:

```
const int size = 7;
void getLottoPicks(int userNum[size]) { //collects and stores the user input
for (int i = 0; i < size; i++) {
cout << "Please enter number " << i+1 << ": ";
cin >> userNum[i];
if (userNum[i] < 1 || userNum[i] > 40) {
cout << "The number must between 1 and 40." << endl
<< "Please enter another number: ";
cin >> userNum[i];
}
for (int j = i; j > 0; --j) {
if (userNum[i] == userNum[j]) {
cout << "Already entered this number";
}
}
}
}
```

Source (Stackoverflow)