c++ - Create random binary string: how to remove null character '\0' from to_string() before inserting to another string -


i trying create random binary string consists of 0s , 1s. in implementation generate random integers 0s , 1s, , use std::to_string() in order typecast them string , insert them string. problem have seems using std::to_string() in order insert '0' or '1' characters, insert terminating null character '\n' , therefore double size of string. example, want create string consisting of nbits=10 characters. implementation below 10 elements string printed on screen, size of string double that. know how avoid this?

the problem size trying write binary representation of genetic algorithm, , need size correct 1 crossover/mutation operators correct.

#include <iostream> #include <string> #include <random>  using namespace std;  std::random_device rd;     std::mt19937 gen(rd());  // random bit string generator  string random_string(size_t nbits){     std::uniform_int_distribution<> int1(0,1);     string s;     s.resize(nbits);     for(size_t i=0; i<nbits; i++)             s.insert(i,to_string(int1(gen)));      return s; };  int main(){     // want 10 bits random binary string      size_t nbits=10;     string s=random_string(nbits);      // if print string on screen, has correct number of entries:      cout<<s<<endl;     // size of string not equal number of entries.      cout<<  "number of bits is: "<< nbits<<", length of string "<< s.size()<<endl;  } 

possible output:

1001111111 number of bits is: 10, length of string 20 

your insertion logic converting values doesn't need to. there no reason convert data string of bits know possible outcomes of each bit: 0 or 1.

and .insert() wrong method. you're stacking data string sized, thereby adding more chars, not replacing them. should start empty string, push data in, reserving if desired (but not required).

try this:

std::string random_string(size_t nbits) {     std::uniform_int_distribution<> int1(0,1);     string s;     s.reserve(nbits);     (size_t i=0; i<nbits; i++)         s.push_back(int1(gen) ? '1' : '0');     return s; }; 

alternatively, exploit fact '0' , '1' guaranteed contiguous values per standard, , perhaps instead:

std::string random_str(size_t nbits) {     std::string s;     std::generate_n(std::back_inserter(s), nbits,         std::bind(std::uniform_int_distribution<char>('0', '1'),std::ref(gen)));     return s; } 

there multitude of ways this, few mentioned here. best of luck.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -