c++ - How to create a function which randomly jumbles a string -
my main function contains string jumble. have found piece of code passes in char*
, returns 0 when complete. have followed code providers instructions pass in string have jumbled.
#include <iostream> #include <string.h> #include <time.h> using namespace std; int scramblestring(char* str) { int x = strlen(str); srand(time(null)); for(int y = x; y >=0; y--) { swap(str[rand()%x],str[y-1]); } return 0; }
when this, recieve error "no suitable conversion function "std::string" "char*" exists
.
i have tried passing in const char*
won't allow me access word , change it.
why mixing std::string
char*
? should operate directly on string:
void scramblestring(std::string& str) { int x = str.length(); for(int y = x; y > 0; y--) { int pos = rand()%x; char tmp = str[y-1]; str[y-1] = str[pos]; str[pos] = tmp; } }
usage becomes:
std::string value = "this test"; scramblestring(value);
that being said, std::random_shuffle you...
Comments
Post a Comment