Home > Mobile >  generate a name in c randomly
generate a name in c randomly

Time:12-23

 signed char *tab_alphabet[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","\0"};

int nombreAlea(int min, int max){
      return (rand()%(max-min 1)   min);
    }
void generer_name(int length,signed char* n){
  int i ;
  signed char *j;
  for (i=0;i<length;i  ){
    int k = nombreAlea(1,26);// from the table of the alphabet
    j = tab_alphabet[k-1];
    strcat(n,j); 
  }
}

here s the main :

int main () {
    int a = nombreAlea(4,30);
   signed char *nn;
    generer_name(a,nn);
    return 0 ;
}

The problem is that the result always is preceeded with "a!!@" , any help , i have a doubt on the strcat

CodePudding user response:

You need to call srand with a different value, classic way is to use time for that.

Use a char[] big enough to store the generate string

Use a simple string as alphabet.

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


char *tab_alphabet="abcdefghijklmnopqrstuvwxyz";

int nombreAlea(int min, int max){
    return (rand()%(max-min 1)   min);
}
void generer_name(int length, char n[]){
    int i ;
    for (i=0;i<length;i  ){
        int k = nombreAlea(1,26);// from the table of the alphabet
        n[i] = tab_alphabet[k-1];
    }
    n[i] = '\0';
}

int main (void) {
    char nn[64];
    int a;
    srand( time( NULL ) );
    a = nombreAlea(4, 30);
    generer_name(a, nn);
    printf(" >%s<\n", nn);
    return 0 ;
}
  • Related