0

Now I've this code:-

The code is about taking in an integer and providing its binary form in the given number of bits.

#include <iostream>
#include <bitset>
using namespace std;

int main(){

    //creating instance using bitset (6 bit). here you can specify the  length such as  8,16,32,64...
    int n=5;
    bitset< 6 > btFlaged;

    //assigning integer value to instance
    btFlaged = 7;

   //print bit string in the string
   for(int i=btFlaged.size()-1;i>-1;i--)
   {
     cout <<btFlaged.test(i);
   }

} 

How do I use an integer(E.g. n) in the place of '6' so that a value entered at run-time can be used in the code?

I've done some research on the net and I know that bitset needs a value at compile time and so instead of bitset, I should use vector bool but I don't know how I should incorporate that in the program?

If any of you guys can tell me how to use vector or if you have an altogether different theory on how to the the task done, please do share.
Also I cant use boost:dynamic_bitset as the code is going to be judged by an online judge which may not have the seperate header file.

1 Answers1

1

a std::bitset's size must be set at compile time as it is a template parameter. If you need a dynamic bitset you can look at boost:dynamic_bitset

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • i would'nt want to use a different header file as my final code is going to be judged by an online judge ...it may not have the seperate header file – Tejas Singh Bedi Jul 31 '15 at 12:39
  • @TejasSinghBedi Can you please explain what part of using a vector bool is confusing you then in your question? – NathanOliver Jul 31 '15 at 13:25
  • how and where do i put vector in the programme ? after incorporating it what will be the code?? – Tejas Singh Bedi Jul 31 '15 at 15:00
  • You might want to look at some tutorials. IMHO `vector` is a pain to work with. one tutorial: http://www.linuxtopia.org/online_books/programming_books/c++_practical_programming/c++_practical_programming_192.html – NathanOliver Jul 31 '15 at 15:16
  • Didn't understand a thing !! No problem ill make the code work without bitset... – Tejas Singh Bedi Jul 31 '15 at 15:30