Hey there!
I'm trying to figure out how to get a random letter generator for a program I'm working on in my computer science class (it's in C++). I need to generate 5 random capital letters between A and P (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P).
I'm not sure how to do it properly (I have no clue if I'm doing this even remotely correct) so any help would be so awesome!

Thanks!!

This is what I have so far:

for (i=0; i<5; i++){
         cmptChoice [i] == rand() % ('A' - 'P');
         }
         cout << "computer choice: " << cmptChoice;
         }

Recommended Answers

All 6 Replies

'A' - 'P' results in a negative number.

rand() % 16 + 'A'

or
rand() % ('P' - 'A') + 'A';

'A' - 'P' results in a negative number.

rand() % 16 + 'A'

or
rand() % ('P' - 'A') + 'A';

Okay thank you so much!!!!

Well I changed the code and now I'm getting 5 random capital letters (so thank you for that) but now it's also outputting bits of random things (random bits of memory purhaps?)... It looks like this:

The computer will now make it's selection.
computer choice: JDOEBr░ý■   b◄Sw─[Xw░╠@
Press any key to continue . . .

How do I fix that? Or can I?
This is what my code looks like now:

cout << "The computer will now make it's selection." << endl;
     for (i=0; i<5; i++){
         cmptchoice [i] = rand() % 16 + 'A';
         }
         cout << "computer choice: " << cmptchoice;

Without seeing the declaration of cmptchoice it is a little speculative as to what your problem is. Having said that, you can't output an array with a single call to <<. You will either have to output each element in cmptchoice individually or you will need to change cmptchoice from a simple array of type char to a string by placing a null char at cmptchoice[5], assuming you have declared enough memory in cmptchoice to allow you to do that without overwriting the array.

my guess is that you failed to null-terminate the string

my guess is that you failed to null-terminate the string

you were very correct :$ I null-terminated the string and it works like a charm now :) Thank you everybody!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.