PROBLEM Read bit size keyboard and use bitset


As I can read the bit size keyboard and use that data with BITSET , can enter the correct code.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <bitset>
using namespace std;

int main()
{
int b,x = 12;
cin>>b;
cout<< bitset<b> (x);
}
Template arguments need to be a compile time constants so you can not let the user decide the size at runtime.
Last edited on
Use a sequence container holding bool values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <deque>

std::ostream& operator<< ( std::ostream& stm, const std::deque<bool>& bits )
{
    for( const auto& b : bits ) stm << ( b ? '1' : '0' ) ;
    return stm ;
}

std::deque<bool> to_bits( std::size_t nbits, unsigned long long value )
{
    std::deque<bool> bits ;

    do
    {
        bits.push_front( value%2 ) ;
        value /= 2 ;
    } while( value > 0 ) ;

    while( bits.size() < nbits ) bits.push_front(false) ;
    return bits ;
}

int main()
{
    std::size_t b ;
    std::cin >> b ;

    const int x = 12 ;
    std::cout << to_bits( b, x ) << '\n'
              << to_bits( 50, 12345678 ) << '\n' ;
}

http://coliru.stacked-crooked.com/a/3bb51d6b290c626c
closed account (48T7M4Gy)
http://www.cplusplus.com/forum/beginner/192968/
Topic archived. No new replies allowed.