Generating random strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cameliachristina
    New Member
    • Jan 2007
    • 1

    Generating random strings

    How do you generate random strings in C?

    Thank you.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Random strigs of letters?

    A crude method would be to generate a random number between 0 and 25 and add it to the character constant 'A' to get a letter. Then store the letters sequencially in a string terminating it with a zero terminator when you have enough letters.

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      Banfa's method will give you nonsense words that are 'randomized', a.k.a. "SJAORYEBRK ".

      If you mean randomly choose a word from a list of given words, generate a random number between 0 and the size of the list - 1, then select that word. For example:

      Code:
      string words[5] = {"Cat", "Dog", "Admin", "TheScripts", "Computer"};
      int pos = rand() % 5;
      cout << words[pos] << endl; // Randomly prints one of the above words
      You will need to build your own list of words somehow.

      EDIT: This code is for C++, you may have to use printf, etc for C

      Comment

      • KittenTheSquid
        New Member
        • Sep 2014
        • 1

        #4
        The idea is right, but you need to seed it.

        #include <iostream>
        #include <stdlib.h>
        #include <time.h>
        using namespace std;

        int main(){
        string words[5] = {"Cat", "Dog", "Admin", "TheScripts ", "Computer"} ;
        srand ((unsigned int)time(NULL)) ; // seeds the random [object] generator
        int pos = rand() % 5;
        cout << words[pos] << endl; // Randomly prints one of the above words
        }

        Comment

        Working...