I know how to generate numbers like 1-20, 1-1000 etc...
but Im trying to figure out how to generate random letters from A-Z?
any help please?
artisabang
0
Newbie Poster
Recommended Answers
Jump to Postdefine a string literal
const char* const a_to_z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
generate a random integer
ri
in the range 0 to 25 (inclusive).
usea_to_z[ri]
as the random letter.
note: *do not* do this:char( 'A' + ri )
Jump to PostLook at an ascii chart -- the letters 'A' - 'Z' have decimal values of 65 - 90. So just generate a random number between 0 and 26 then add 65.
Jump to Postnote: *do not* do this:
char( 'A' + ri )
Vijayan is saying this because it is not guaranteed that the character set will have the alphabetical characters
'A'
through'Z'
or'a'
through'z'
represented by a contiguous block of integers. However, it is very likely. Some character …
Jump to Postint main() { int n = rand() % 26; char c = (char)(n+65); cout << c << "\n"; return 0; }
All 13 Replies
vijayan121
1,152
Posting Virtuoso
artisabang
0
Newbie Poster
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
artisabang
0
Newbie Poster
vmanes
1,165
Posting Virtuoso
sarehu
84
Posting Whiz in Training
vmanes
commented:
Nice clear response
+2
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
orbidden
commented:
Thanks, You were very clear and percise, it was very easy to understand.
+0
vmanes
1,165
Posting Virtuoso
Ancient Dragon
5,243
Achieved Level 70
Team Colleague
Featured Poster
vmanes
1,165
Posting Virtuoso
vijayan121
1,152
Posting Virtuoso
skatamatic
371
Practically a Posting Shark
WaltP
2,905
Posting Sage w/ dash of thyme
Team Colleague
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.