开发者

how randomly select the word from 26 letters using C language?

I want codes for randomly selects the word (meaningful or meaning开发者_StackOverflow中文版less) from 26 letters. The word contain 6 letters. I have the codes for C program or objective C, or you will give any idea to me.


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main()
{
    srand(time(NULL));
    for (int i = 0; i < 6; ++i)
    {
        putchar('a' + (rand() % 26));
    }
    putchar('\n');
    return EXIT_SUCCESS;
}

Salt to taste.

Update0

It would seem the OP does not know how to compile the above. If saved into a file called so.c, compile it with make so CFLAGS=-std=c99 from the same folder.


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* Written by kaizer.se */
void randword(char *buf, size_t len)
{
  char alphabet[] = "abcdefghijklmnopqrstuvxyz";
  size_t i;

  for (i = 0; i < len; i++) {
    size_t idx = ((float)rand()/RAND_MAX) * (sizeof(alphabet) -1);
    buf[i] = alphabet[idx];
  }
  buf[len] = '\0';
}

int main(void) {
  char buf[1024];

  srand(time(NULL));

  randword(buf, 7);
  printf("Word: %s\n", buf);
  return 0;
}

Test:

$ ./rword 
Word: xoilfvv
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜