0

I want to make proggram wchich will be generete numbers in binary base from o to n, and i want thme all have the same numbers of chars. That's the code:

#include <iostream>
#include <bitset>
#include <string>
#include <vector>
#include <cmath>
#include <stdio.h>
using namespace std;  
vector<string> temp;
int BinaryNumbers(int number)
    { 
        const int HowManyChars= ceil(log(number));
        for(int i = 0; i<number; i++)
        {
            bitset<HowManyChars> binary(i); 
            temp.push_back(binary.to_string());                             
        }
    }

int main(){
    BinaryNumbers(3);
    for(int i=0; i<temp.size();i++)
    {
        cout<<temp[i]<<endl;
    }
    return 0;
}

My problem is that I can't set bitset<> number(HowManyChars)"[Error] 'HowManyChars' cannot appear in a constant-expression"

  • 1
    Possible duplicate of [Define bitset size at initialization?](https://stackoverflow.com/questions/3134718/define-bitset-size-at-initialization) – Killzone Kid May 06 '18 at 17:02

2 Answers2

0

A possible solution is to use the maximum sized bitset to create the string. Then only return the last count characters from the string.

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
0

In C++17 there is a new function to_chars. One of the functions (1), takes the base in the last parameter.

// use numeric_limits to find out the maximum number of digits a number can have
constexpr auto reserve_chars = std::numeric_limits< int >::digits10 + 1; // +1 for '\0' at end;

std::array< char, reserve_chars > buffer;

int required_size = 9; // this value is configurable

assert( required_size < reserve_chars ); // a check to verify the required size will fit in the buffer

// C++17 Structured bindings return value. convert value "42" to base 2.
auto [ ptr, err ] = std::to_chars( buffer.data(), buffer.data() + required_size, 42 , 2);

// check there is no error
if ( err == std::errc() )
{
    *ptr = '\0'; // add null character to end
    std::ostringstream str; // use ostringstream to create a string pre-filled with "0".
    str << std::setfill('0') << std::setw(required_size) << buffer.data();

    std::cout << str.str() << '\n';
}
Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31