C ++ How to assign input value to std :: bitset argument?

I want to create a simple program that will take the number of bits from input and as output binary numbers of output written on given bits (example: I type 3: shows 000, 001, 010, 011, 100, 101, 110, 111). The only problem I get is in the second for-loop when I try to assign a variable to bitset < bits > but it wants a constant number. If you could help me find a solution, I would be very grateful. Here is the code:

#include <iostream>
#include <bitset>
#include <cmath>

using namespace std;

int main() {
    int maximum_value = 0,x_temp=10;
    //cin >> x_temp;
    int const bits = x_temp;

    for (int i = 1; i <= bits; i++) {
        maximum_value += pow(2, bits - i);
    }
    for (int i = maximum_value; i >= 0; i--)
        cout << bitset<bits>(maximum_value - i) << endl;
    return 0;
}
+4
source share
2 answers

( "-", ++) , . (, 64). , :

int x_temp = 10;
cin >> x_temp;
int const bits = 64;
...

64 - - , , bitset unsigned long long, 64 ( , ).

, int , 14 ( ). 14 (, 64), , uint32_t uint64_t.


, , , . , substr:

cout << bitset<64>(...).to_string().substr(64 - x_temp);

to_string 64 , substr , x_temp.

+1

const int bits = 10; :

#include <iostream>
#include <math.h>
#include <bitset>

using namespace std;
const unsigned bits=10;
int main() {
    int maximum_value = 0,x_temp=10;

    for (int i = 1; i <= bits; i++) {
        maximum_value += pow(2, bits - i);
    }
    for (int i = maximum_value; i >= 0; i--)
        cout << bitset<bits>(maximum_value - i) << endl;
    return 0;
}

enter image description here

0

Source: https://habr.com/ru/post/1658255/


All Articles