I want to create an array of Bitset .Binary Bitset(example "100","1010",etc) After that I want to input from user and store in the the Bitset . I have tried the following line but it says error.
#include<bits/stdc++>
using namespace std;
int main()
{
int n,i;
string bit_string;
cin>>n // size of Bitset array.
bitset<8> brr[n];//
for(i=0;i<n;i++)
{
cin>>bit_string;
brr[i](bit_string);
}
return 0;
}
I want to create n Bitset each of size 8 bits.Where n is given by user. my input is binary string like. "110010","001110" please help
The error ocurrs because you are trying to creat a C-style array using n
which is not compile-time constant. It's not possible to creat a C-style array without being n
known at compile time.
The following is a good way to do what you want
Creat a std::vector<std::bitset<8>>
to hold your bitset<8>
s, as follows.
Note that the code ignores the excess of characters in strings iput like "111111110"
(makes it "11111111"
) and treats any character except '1'
as if it were '0'
and if the input string is less than 8 characters, the code adds zeros by the default of the bitset
s
#include <vector>
#include <bitset>
#include <iostream>
int main() {
int n, i;
std::string bit_string;
std::cout << "Enter the size";
std::cin >> n; // size of Bitset array.
std::vector<std::bitset<8>> brr(n);//
for (i = 0; i < n; i++) {
std::cin >> bit_string;
for (int j{}; j < bit_string.size() && j < 8; ++j) {
brr[i][j] = (bit_string[j] == '1') ? 1 : 0;
}
}
//To test
for(auto const& el :brr)
{
for(int i{}; i < 8;)
std::cout << el[i++];
std::cout<<"\n";
}
}
See Why is "using namespace std;" considered bad practice? and Why should I not #include <bits/stdc++.h>?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With