954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

ASCII Problem

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?

VP2
Newbie Poster
4 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

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.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

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!

VP2
Newbie Poster
4 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

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.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: