Hello everyone!
I'm trying to make a game where the program gives you a random number(char) from an array.
The problem is that for some reason it keeps returning more than 1 number. I only want the program to give me one number only.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void arrfunct(char arr[], int pick) {
for (int i = pick; i < 5; i++) {
cout << "\n" << "|" << arr[i] << " |";
}
cout << endl;
}
int main() {
char arr[5] = {"A","B","C","D","E"};
int randomize;
srand(time(NULL));
random = rand() % 4 + 0;
arrfunct(arr, randomize);
return 0;
}
I understand I can do if statements to to return the array with the "|" symbol, but I want to have it that way in the function because later I will need the function instead of re-writing long codes.
your random number is called random. you call the function with randomize, which is not initialized.
arrfunct loops and prints, it can print none or one or many depending on the uninitialized value passed into it. Printing and doing work together are ok for small programs but you usually want to split them, as in the code above. Doing them together is two things to debug at once when testing it and it is also less flexible (what if later you want a random value, but don't want to print it?).
I managed to get it fixed without having to make a loop. I just added another argument and used that when calling the function. Just set another randomize + 1 inside where we call the function. Problem fixed! Thanks guys!