CodeFu
CodeFu

Reputation: 165

Take input in array of bool

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!!

Upvotes: 0

Views: 1472

Answers (3)

antonpp
antonpp

Reputation: 2373

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;
}

Upvotes: 1

Barry
Barry

Reputation: 303057

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.

Upvotes: 6

Andreas Vennstr&#246;m
Andreas Vennstr&#246;m

Reputation: 715

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 );

Upvotes: 2

Related Questions