How to create a function which randomly jumbles a

2019-08-30 12:27发布

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.

5条回答
爷的心禁止访问
2楼-- · 2019-08-30 12:54

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.

查看更多
爷的心禁止访问
3楼-- · 2019-08-30 12:54

If you want to write random char data into a string, the C++ way using random library is:

#include <random>

std::string mystring = "scramble this please";

std::default_random_engine rng;
std::uniform_int_distribution<int> rng_dist(0, 255);
for(unsigned int n = 0; n != mystring.size(); ++n) {
  mystring[n] = static_cast<unsigned char>(rng_dist(rng));
}
查看更多
叛逆
4楼-- · 2019-08-30 12:56

Why are you mixing std::string with char*? You should just operate directly on the 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 is a test";
    scrambleString(value);

That being said, std::random_shuffle will do this for you...

查看更多
一夜七次
5楼-- · 2019-08-30 12:57

Try this instead:

std::string s = "Hello";
std::random_shuffle(s.begin(),s.end());

By the way, don't forget to include <algorithm> in order to use std::random_shuffle, and you need to include <string> for std::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.

查看更多
叼着烟拽天下
6楼-- · 2019-08-30 12:57

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.

查看更多
登录 后发表回答