I've pieced together a small program designed to build random names. It is not finished, however it is currently repeating the same name if I attempt to re-run the program. Program is built on Ubuntu Linux, C++ running the emacs text editor.
Here is the full code below, I am still fairly new to C++ but haven't encountered this issue before.
#include <iostream>
#include <vector>
#include <iomanip>
#include <stdlib.h>
using namespace std;
string randomName(int length) {
char consonents[] = {'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','z'};
char vowels[] = {'a','e','i','o','u','y'};
string name = "";
int random = rand() % 2;
int count = 0;
for(int i = 0; i < length; i++) {
if(random < 2 && count < 2) {
name = name + consonents[rand() % 19];
count++;
}
else {
name = name + vowels[rand() % 5];
count = 0;
}
random = rand() % 2;
}
return name;
}
int main() {
cout << "Enter a name length: " << endl;
int length;
cin >> length;
cout << randomName(length) << endl;
return 0;
}
I have read the predictability for rand() and in the other questions that were similar to this they mention that rand() often repeats values. Surely this can't be every single time the program is run though can it?
In example: If I run the program with a name length of 5 I may get something like: tfuvi
If I then run the program a second time with a name length of 2 I will get: tf
If I then run the program a third time with the name length of 4 I will get: tfuv
This can't be coincidence right?
Any help is greatly appreciated, if there is any documentation that explains this or if anyone knows a reason please let me know, thanks.
Aucun commentaire:
Enregistrer un commentaire