My main function contains a string that I would like to jumble. I have found a piece of code which passes in a char*
and returns 0 when complete. I have followed the code providers instructions to simply pass in the string which you would like to 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 I do this, I recieve an error that "no suitable conversion function "std::string" to "char*" exists
.
I have also tried passing in a const char*
but that won't allow me to access the word and change it.
Try using it like this:
std::string stringToScramble = "hello world";
scramble(stringToScramble.c_str());
Notice the use of .c_str() which should convert the string into the format that you need.
If you want to write random char data into a string, the C++ way using random library is:
Why are you mixing
std::string
withchar*
? You should just operate directly on the string:Usage becomes:
That being said, std::random_shuffle will do this for you...
Try this instead:
By the way, don't forget to include
<algorithm>
in order to usestd::random_shuffle
, and you need to include<string>
forstd::string
.<string.h>
is for the c-string library, and if you're going to use that in C++, you should actually use<cstring>
instead.std::string class cannot be converted to char* implicitly. You have to use string.c_str() to convert to const char* from std::string.
Notice c_str() returns a const pointer to the string copied from std::string internal storage so you cannot change its content. instead, you have to copy to another array or vector.