Random Number using Function

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.
Are you looking for something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>

char a_random_char_from( const char cstr[] )
{
    const std::size_t num_chars = std::strlen(cstr) ;
    return cstr[ std::rand() % num_chars ] ;
}

void print_a_random_char_from( const char cstr[], const char* prefix = "\n|", const char* suffix = "|\n" )
{
    std::cout << prefix << a_random_char_from(cstr) << suffix ;
}

int main()
{
    std::srand( std::time(nullptr) ) ;
    const char char_set[] = "ABCDE" ;

    /* for( int i = 0 ; i < 10 ; ++i ) */ print_a_random_char_from(char_set) ;
}
couple of details on what could be confusing you:

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!
Last edited on
Topic archived. No new replies allowed.