generate random characters in c [duplicate]

2019-02-09 12:50发布

问题:

This question already has an answer here:

  • How to generate a random integer number from within a range 11 answers

I'm new to programming in C and have been given the task of creating a 2D array that stores random letters from A-Z using the random () function. I know how to do random numbers.

nextvalue = random ( ) % 10001;

but am unsure on how exactly to create a random character. I know that you can use ASCII to create a random character using the range 65 - 90 in the ASCII table. Can anyone help me come up with a solution? I would greatly appreciate it.

回答1:

You should assume something about the character encoding of your system. Let's suppose it is ASCII or UTF-8 and let us restrict ourselves to the 26 upper-case letters ABC...XYZ of the latin alphabet.

Then you could code:

 char randomletter = 'A' + (random() % 26);

This won't work on EBCDIC. You could also try

 char randomletter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random () % 26];

which would work with any encoding (including EBCDIC, ASCII, UTF-8, ISO-Latin-1) ....where each A...Z letter is encoded by a single char.

But this is an interesting answer explaining why random() % 26 is wrong. In my naive non-expert view, it is good enough.

Replacing random() % 26 by myrandomlt26() where we have defined

static inline unsigned myrandomlt26() {
   long l;
   do { l = random(); } while (l>=(RAND_MAX/26)*26);
   return (unsigned)(l % 26);
}

should be slightly better (Very often the do...while loop above should run once).

However, learn more e.g. about Unicode, you'll discover that there are some human languages where the very notion of letter (or upper-case) is not as trivial as you believe.

I'm not an expert on these matters, but urban legend says that strangely the French œ is not a letter (but just a ligature) because the French representative at some ISO meeting was sick when it was discussed. At French school, I recall having learned (probably in 1966-1972) that it is not a letter (but not hand-writing the ligature -which has a special name "E dans l'O" in French- was a spelling mistake), but some people believe the opposite. Usually accented letters like é or à are considered letters in French (but their UTF-8 encoding takes several consecutive char....). Likewise I believe and have learned that the cyrillic soft-sign ь is not a letter, even if it looks like one. Defining what is a letter in arabic, hebrew, korean, cherokee, thai ... should also be fun and matter of endless debates...



回答2:

I think you have already solved this problem. You just need to think harder and tinker more with it. In C you can easily display any ASCII character in Dec form. Here is the ASCII Table for reference. For example

char c = 65;
char c = 'A'; // Both are the same thing.

So it is probably the same as generating a random number between 65 and 90. Hope this helps ;) Am also new to C with some background in C++.