0

I want to take input in array of bool

bool bmp[32];

And this will be the program interaction.

 Enter binary number : 10101

I want to store user input of '10101' in array of bool like.

bmp[32]={1,0,1,0,1};

Please help!!

3 Answers 3

6

Since this is C++, let's use std::bitset:

std::cout << "Enter binary number : ";

std::bitset<32> b;
std::cin >> b;

It's not a bool array like you requested - but it's way better.

Sign up to request clarification or add additional context in comments.

3 Comments

...or a way worse=) In my personal opinion I would use a single int as a binary mask for this case.
@Anton And if you want 132 bits instead of 32?
then it is another story to tell. I simply mean that the solution strongly depends on the task and std::bitset is not always the right choice when you need some work to be done over the bloody bits.
2

This should work, but try something out on your own next time (and post the code you tried).

bool b[ 32 ];
std::string str = "10101";
for ( std::string::size_type i = 0U; i < str.length(); ++i )
    b[ i ] = str[ i ] == '1';

Or maybe

std::vector< bool > b;
std::string str = "10101";
b.reserve( str.length() );
for ( const char c : str )
    b.push_back( c );

Comments

1

Nothing fancy, just read data and store it to array like this:

#include <string>
#include <cstdio>

int main() {
    std::string str;
    std::cout << "Enter binary number : ";
    std::cin >> str;
    bool b[32];
    std::size_t size = 0;
    for (auto c : str) {
        b[size++] = c == '1';
    }

    // you are all set now.

    return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.