I want to create a bitset with a size that I input, something like this:
int a;
int main() {
cin >> a;
const int l = a;
cout << bitset<l>(123);
}
But when I run this code I receive these errors:
jdoodle.cpp:11:21: error: the value of ‘l’ is not usable in a constant expression
11 | cout << bitset<l>(123);
| ^
jdoodle.cpp:6:11: note: ‘l’ was not initialized with a constant expression
6 | const int l = a;
| ^
jdoodle.cpp:11:21: note: in template argument for type ‘long unsigned int’
11 | cout << bitset<l>(123);
It works fine when I set l to some integer like const int l = 6 but I get errors when I change it to const int l = a. How can I fix this?
*Edit: Thanks to those people who helped me out, I think I figured out what I need to do. I can create a bitset with a big size then I can just ignore the bits that are longer than my input.
The short answer is, you can't. For
std::bitset, the size needs to be determined at compile-time. See here: https://www.cplusplus.com/reference/bitset/bitset/"The size of a bitset is fixed at compile-time (determined by its template parameter). For a class that also optimizes for space allocation and allows for dynamic resizing, see the bool specialization of vector (vector)."
Here is the link to the vector specialization: https://www.cplusplus.com/reference/vector/vector-bool/