Jump to content

how to use rand() in char

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
7 replies to this topic

#1
iamanoob

iamanoob

    Newbie

  • Members
  • Pip
  • 6 posts
how to use rand() to get random char between A and Z;
and how to get random int between -9 to 9.

#2
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Do you want just A-Z capitalized or Aa-Zz? If you look at a ASCII chart you can see that A-Z is 65-90 so you need to generate a random number between those values:

*/ Declare our High and Low */
const int LOW = 65;
const int HIGH = 90;

*/ Char to hold our Ascii /*
char buffer [1];

*/ Seed the random number */
srand((unsigned int) seconds);

*/ Generate the number */
number = rand() % (HIGH - LOW + 1) + LOW;

*/ Convert to ASCII */
itoa (number,buffer,10);



With that code buffer will now hold your char. You could also just print it out with:


 printf("Ascii %s\n",  itoa(number, buffer, 10));

Moving this thread to the correct forum.

#3
gaffney2010

gaffney2010

    Newbie

  • Members
  • Pip
  • 2 posts
That was a good explanation...

To get an integer between -9 and 9

int a=rand%19;   //random int between 0 and 18

a-=9;   //random int between -9 and 9


#4
iamanoob

iamanoob

    Newbie

  • Members
  • Pip
  • 6 posts
thx for help.. but Jordan can u pls try to make the code in one function, becasue i cant really understand what the code is...and how to use it...sry...

#5
iamanoob

iamanoob

    Newbie

  • Members
  • Pip
  • 6 posts
Jordan i try ur code, it can work but the result given is still a int value...and may i know what is this;

itoa (number,buffer,10);


#6
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
itoa is a non-standard function, and will not work right with all compilers. You can solve easily convert integers into characters by using a simple cast, like (char).
int GetRandom(int iMin, int iMax)
{
	return rand() % (iMax - iMin + 1) + iMin;
}
This is how your function should look like. As you see, it's actually just Jordan's code put into a function. You need to seed rand (srand) outside the function, right before you call it.

#7
DevilsCharm

DevilsCharm

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 884 posts
Do you need to use rand(); in conjunction with ASCII to make the program work?

#8
Guest_Jordan_*

Guest_Jordan_*
  • Guests
No, but iamanoob needed "rand() to get random char" between A-Z. That is the purpose of rand in this thread.