Generate random characters in c

I am new to C programming and have been given the task of creating a 2D array that stores random letters from AZ using the random () function. I know how to make random numbers.

nextvalue = random ( ) % 10001; 

but I'm not sure how to create a random character exactly. I know that you can use ASCII to create a random character using the range 65 - 90 in an ASCII table. Can someone help me come up with a solution? I would be very grateful.

+6
source share
2 answers

You should accept something about the character encoding of your system. Suppose it is ASCII or UTF-8 and let's limit ourselves to 26 uppercase letters ABC ... XYZ of the Latin alphabet.

Then you can enter the code:

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

This will not work on EBCDIC . You can also try

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

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

But this one is an interesting answer explaining why random() % 26 is incorrect. In my naive non-expert look, this is good enough.

Replacing random() % 26 with myrandomlt26() , where we defined

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

should be a little better (very often the do ... while above should run once).

However, learn more, for example. about Unicode , you will find that there are some human languages ​​where the very concept of a letter (or uppercase) is not as trivial as you think.

I am not an expert on these issues, but the urban legend says that strange French is not a letter (but only a ligature), because the French representative at some ISO meeting was ill when he was discussed. In a French school, I remember that when I found out (possibly in 1966-1972) that this was not a letter (but not a letter-letter from the ligature, which in French has the special name "E dans l'O"), it was a spelling mistake ), but some people believe the opposite. Usually accented letters of type Γ© or Γ  are considered letters in French (but their UTF-8 encoding takes several consecutive char ....). In the same way, 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 the stuff of endless debate ...

+24
source

I think you have already solved this problem. You just need to think more and do more with it. In C, you can easily display any ASCII character in the form of Dec. The following is an ASCII table . for instance

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

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

+1
source

Source: https://habr.com/ru/post/957175/


All Articles