CreamyWeamy11 CreamyWeamy11 - 1 year ago 84
C Question

Characters Stored in String - How to Store them in another String variable when randomized

Good day! I'm a newbie programmer and I am still confused with how to apply the concepts of C.

I am working on a project. My problem is that I have INITIALIZED certain characters and have stored them in a string (vars[28]). My goal is to generate the characters of the string in a random manner and to store the generated string in another variable, which I do not know how to.

int randnum = 0, num = 0;
char vars[28] = "|abcdefghijklmonpqrstuvwxyz."; //initialized string
char term; //where to store randomized string
int i = 0;
char choi[1];

printf ("%c", vars[0]);

srand (time(NULL));
randnum = rand() % 30; //only 30 characters maximum to be stored

for (i = 0; i <= randnum; i++)
//randomly produce vars[28] characters here and store into 'term'

Additional question: How do I prevent | and . to be beside each other when randomized?

Thank you!

Answer Source

term is just single character. A string is an array of characters. Standard C strings end with a 0. So in order to create a random string your program should look like this:

int randnum = 0;
char* vars = "|abcdefghijklmonpqrstuvwxyz."; // array of alowed characters
char term[30 + 1]; // allocating an array of 30 characters + 1 to hold null terminator
int i = 0;

srand (time(NULL));
int length = rand() % 30 + 1; // random length up to 30, minimum 1 character (the +1)

for (i = 0; i < length; i++)
    randnum = rand() % 28; // random index to the array of allowed characters
    term[i] = vars[randnum]; // assign random character to i-th position of term
term[i] = '\0'; // end string

printf("%s\n", term);

I strongly suggest you follow up with a lecture on C language though - a couple first chapters (tops), should clear everything!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download