Hello! I've got a little problem... I want to make a program which puts 10 random character, but the characters should NOT be digits.

#include <ctime>
#include <stdio>
#include <iostream>
using namespace std;
int main()
{
    time_t t;
    time(&t);
    srand(t);
    int i,c;
    char ch;
    printf("Generating 10 random characters...\n");
    for(i=1;i<=10;i++)
    {
                      c=rand();
                      ch=c;
                      printf("%c ",ch);
    }
    printf("\n");
    system("PAUSE");
    return 0;
}

I've got an idea, I could add a while and say

while(ch<ASCII HERE&&ch>ASCII HERE)
{
     //generating random characthers
}

But I don't know how to use the ASCII... help?

Edited 5 Years Ago by VP2: n/a

ASCII characters are just numbers. So if you wanted onthe the upper case letters for example, the are 'A' thru 'Z', or 65 thru 90. So
1) limit your random value from 0 to 25 (number of letters)
2) add 'A' or 65 to it.
That will give you all the upper case letters.

Thanks! I solved it like this(only upper case)...

#include <ctime>
#include <iostream>
using namespace std;
int main()
{
    time_t t;
    time(&t);
    srand(t);
    int i,c;
    char ch;
    printf("Generating 10 random characters\n");
    for(i=1;i<=10;i++)
    {
                      do{
                         c=rand();
                         ch=c;
                      }while(ch<65||ch>90);                  
                      printf("%c ",ch);
    }
    printf("\n");
    system("PAUSE");
    return 0;
}

Well, this'll be marked as solved... thanks again!

You can certainly mark the thread solved (that's a good thing -- thanks).
On the other hand, you could make your program work much better.

What you are doing is getting a random value between 0 and at least 32767. and you are looking for 65-90. Basically that means out of 1260 (32767/26) calls to the random function you will get a letter. To get your 10 letters, you'll have to get 12600 random values on average.

You can cut that down to getting 10 numbers with a little thought -- and searching these forums to find out how to make the random numbers fall between 65 and 90 on the first try.

This question has already been answered. Start a new discussion instead.