Hi everbody, I wanted to know, I made a little program that pick a word from a text file than pass the word into a Suffle letters function end then sending me back the result to Main,
string sword ()
{
char* Sdword = NULL;
string Sword = pword();
int word_s = Sword.size();
Sdword = new char[word_s] ;
int word_counter = 0;
srand(time(0));
while (word_counter != word_s)
{
int random = rand() % Sword.size() ;
Sdword[word_counter]= Sword [random];
Sword.erase(random,1);
++word_counter;
}
return Sdword;
}
the Problem is whenever a pick a long word in my dictionary ( about 6 characters or more), it start to add more Characters throught the real shuffled word, like weird accent, capital letters and ASCII weird signs ( all my words are written in normal letters type), I tried a couple time to clear my entire array before each use but in vain.
The weird characters are because there is no null terminator on the c-string. The buffer needs to be longer by one character, and place a zero '\0' in the last position. But do take heed of the other issues, using new without delete gives a memory leak. Better to use std::string instead.
Try replacing
char* Sdword = newchar[word_s];
with
std::string Sdword = std::string(word_s, 0);
Also, make sure the program doesn't call srand() more than once.
In my case I also got my function pword() who s picking a random line in a text file , so when you say to make sure to not call srand () more than once are you talking about calling this statement across many function or calling it once in a specified function
When I mentioned srand() it was a general comment, I wasn't sure of the context.
Usually it is called just once in the entire program, at the start of main().
If the function sword () is called more than once, then the random number generator will be re-seeded each time which makes the numbers less random.