开发者

how to make a name from random numbers?

开发者 https://www.devze.com 2022-12-28 15:46 出处:网络
my program makes a random name that could have a-z this code makes a 16 char name but :( my code wont make the name and idk why :( can anyone show me what\'s wrong with this?

my program makes a random name that could have a-z this code makes a 16 char name but :( my code wont make the name and idk why :( can anyone show me what's wrong with this?

char name[16];
void make_random_name()
{

  byte loop = -1;

  for(;;)
  {
      loop++;

      srand((unsigned)time(0));
      int random_integer;

      random_integer = (rand()%10)+1;

      switch(random_integer)
      {
      case '1': name[lo开发者_运维问答op] = 'A';
          break;
      case '2': name[loop] = 'B';
          break;
      case '3': name[loop] = 'C';
          break;
      case '4': name[loop] = 'D';
          break;
      case '5': name[loop] = 'E';
          break;
      case '6': name[loop] = 'F';
          break;
      case '7': name[loop] = 'G';
          break;
      case '8': name[loop] = 'Z';
          break;
      case '9': name[loop] = 'H';
          break;
      }

      cout << name << "\n";

      if(loop > 15)
      {
          break;
      }

  }


 }


random_integer is an integer, you are comparing it to a bunch of characters from the ASCII character set - '1' as a character literal is actually 49 in decimal. As 49 is not in the range of your random numbers, it'll never get hit.

Try changing your case statements to

case 1: ...

instead of

case '1': ...


srand((unsigned)time(0));

Take this out of the for loop, you need to seed it once only.

case '1':

1 does not mean integer 1, rather it is character 1 which translates (ascii) to integer 49. Change it to -

case 1 :


Or just use

char name[16];
for (i = 0; i < sizeof name; ++i) {
  name[i] = "ABCDEFGHIJ"[rand() % 10];
}


There are so many things wrong with this that I'll list them:

  1. You don't null terminate the string.
  2. You're needlessly using a switch statement for data that could very easily be done with array indexing.
  3. You're calling srand in a loop.
  4. for(;;) { i++ ... -- Really?
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号