how to use rand() to get random char between A and Z;
and how to get random int between -9 to 9.
how to use rand() in char
Started by iamanoob, Nov 02 2007 01:09 AM
7 replies to this topic
#1
Posted 02 November 2007 - 01:09 AM
|
|
|
#2
Guest_Jordan_*
Posted 02 November 2007 - 03:45 AM
Guest_Jordan_*
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:
With that code buffer will now hold your char. You could also just print it out with:
Moving this thread to the correct forum.
*/ 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
Posted 02 November 2007 - 01:26 PM
That was a good explanation...
To get an integer between -9 and 9
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
Posted 02 November 2007 - 08:42 PM
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
Posted 02 November 2007 - 08:49 PM
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
Posted 02 November 2007 - 11:58 PM
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
Posted 07 November 2007 - 05:37 PM
Do you need to use rand(); in conjunction with ASCII to make the program work?
#8
Guest_Jordan_*
Posted 08 November 2007 - 04:39 AM
Guest_Jordan_*
No, but iamanoob needed "rand() to get random char" between A-Z. That is the purpose of rand in this thread.


Sign In
Create Account

Back to top









