1
#include <iostream>
#include <string>
#include <time.h>

using namespace std;

int main(){
    srand (time( NULL));
     const char* words[] = {"Sunday", "Monday", "Tuesday", "Wedensday", "Thursday", "Friday", "Saturday"};


    int Randnum = rand() % 6;
    cout << words[Randnum] << endl;


}

So basically what I want to do is that instead of having that int Randnum = rand() % 6 ;, I want to have a variable that changes with the array. something like int Randnum rand() % totalwords;. I tried using sizeof(words but that would only work if I know how many bytes each word took. Is there any way you guys can think of that would let me count each word as 1 item so when the array grows the random number range does too?

2 Answers 2

5

Use this:

sizeof(words)/sizeof(words[0])

which will give you 7.

And int Randnum = rand() % 7 give you a random number between 0 and 6 and words[Randnum] is a random day in the week.

Sign up to request clarification or add additional context in comments.

Comments

0

Try

sizeof(words)/sizeof(char *)

As the entries in words are char * and the total size of words will be the number of bytes to store the 7 character pointers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.