C++ How can I assign an input value to a std::bitset argument?

后端 未结 2 1439
暖寄归人
暖寄归人 2021-01-19 15:19

I want to make a simple program that will take number of bits from the input and as an output show binary numbers, written on given bits (example: I type 3: it shows 000

2条回答
  •  猫巷女王i
    2021-01-19 15:46

    A numeric ("non-type", as C++ calls it) template parameter must be a compile-time constant, so you cannot use a user-supplied number. Use a large constant number (e.g. 64) instead. You need another integer that will limit your output:

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

    Here 64 is some sort of a maximal value you can use, because bitset has a constructor with an unsigned long long argument, which has 64 bits (at least; may be more).

    However, if you use int for your intermediate calculations, your code supports a maximum of 14 bits reliably (without overflow). If you want to support more than 14 bits (e.g. 64), use a larger type, like uint32_t or uint64_t.


    A problem with holding more bits than needed is that the additional bits will be displayed. To cut them out, use substr:

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

    Here to_string converts it to string with 64 characters, and substr cuts the last characters, whose number is x_temp.

提交回复
热议问题