4
int b;
int array[12];

cout << "Enter binary number: ";
cin >> b;

(for example: b will be 10100)

** How to store b(10100) into an array so that it'll be [1][0][1][0][0] **

cout << array[0] << endl;

** output should be 1 **

cout << array[1] << endl;

** output should be 0 **

Please help thank you.

3
  • not homework but example problems to work on so I won't struggle in class when the semester starts. Commented Aug 3, 2011 at 3:19
  • @Kit Ho and also, as a software engineer do you program and/or use C++? Commented Aug 3, 2011 at 3:31
  • @Junior89 that is a broad question. You will find some engineers that use exclusively C++, some that use it occasionally, and some that never have to touch it. Commented Aug 3, 2011 at 4:07

5 Answers 5

9

A string can also be treated as an array of chars. So you can get input into a string, instead, and the cout statements you wrote, should work. However, they will be chars and not ints, so you would be storing '1' and '0' instead of 1 and 0. Converting between them is easy, just use array[0]-'0'

#include <string>
#include <iostream>

using namespace std;

int main()
{
  string array;
  cout << "Enter binary number: "; cin >> array;
  // Suppose the user inputs 10100
  cout << array[0] << endl; // outputs '1'
  cout << array[1] << endl; // outputs '0'
  cout << array[2] << endl; // outputs '1'

  return 0;
}

Update: Added compilable code. Note that this is pretty much the original code posted with the question, except for inputting a string.

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

7 Comments

The OP isn't using a string anywhere.
thank you I appreciate your help, but where do I go from what you wrote? lol sorry im new to this, I just can't figue out how to actually "store" the binary into an array
@Chris I agree he wasn't using it, however, I believe it's the simplest way to solve the problem as he posted it (or rather, as I understood it!).
@Junior89 cin >> array stores whatever the user inputs into the array variable. Maybe I'm not understanding what you're asking.
@Pablo cout << "Enter binary number: "; cin >> binarynumber; store binarynumber into an array so that when I call array[1] from the binary number 10100, a zero should output, or if I call array[2] then a 1 should output from the array. What I do not know how to do is store the input binary number into an array so that it would [1][0][1][0][0] lol, you understand what I'm trying do?
|
1

I had originally wrote up an answer similar to Pablo, but seeing as he already posted it, here is one more consistent with the information given.

It takes an int input and places it into an int array.

#include <iostream>
#include <cmath>

int main( )
{
    int b;
    int numDigits;

    // Get bit string int
    std::cin >> b;

    // Get the number of digits
    numDigits = std::floor( std::log10( ( float )std::abs( b != 0 ? b : 1 ) ) ) + 1;

    // Dynamically create a new array of the appropriate size
    int* arr = new int[ numDigits ];

    // Initialize all the blocks of memory
    std::memset( arr, 0, numDigits );

    // Fill the array
    for( int i = 0; i < numDigits; i++ )
    {
        arr[ numDigits - i - 1 ] = b % 10;
        b /= 10;
    }

    system( "PAUSE" );

    // Delete the array
    delete [] arr;

    return 0;
}

This one dynamically sets the size of the array so it fits correctly.

2 Comments

your code runs, but it does not do anything. When I compiled it I inserted the binary numbers and then tried a size but all I got was "Press any key to continue"
@Junior89 Yes, that is intended. The array is filled and it is up to you to do with it as you please. It does nothing but take in the number and split it into an array.
1

The following example stores bits to a raw C-style array as you require. But you can replace it with a std::vector if you want.

int main()
{
  // assume sizeof(int) is 32, or you can use heap-allocated array or std::vector
  int array[32];

  unsigned int mask = 1;
  // mask is initially 0x80000000
  mask = mask << (sizeof(int)*8 - 1);

  int i = 0;

  // we start counting from the first "1",
  // preceding "0"s are ignored to display
  bool started = false;

  int b;
  cin >> b;

  while (mask != 0)
  {
    // if current bit is "1" or "0"
    if (mask & b) 
    {
      started = true;
      array[i++] = 1;
    }
    // if current bit is "0" and counting started
    else if (started)
    {
      array[i++] = 0;
    }
    // ready to test next bit
    mask = mask >> 1;
  }

  // test result
  for (int j = 0; j < i; ++j) cout << array[j];

  cout << endl;
  return 0;
}

Test cases:
1. b = 8  => array: 1000
2. b = -8 => array: 11111111111111111111111111111000
3. ..

Comments

1

You can use boots dynamic bitset

#include "boost/dynamic_bitset.hpp"
#include <sstream>
#include <iostream>

int main()
{
    boost::dynamic_bitset<>     val;
    std::stringstream           input("1010101010");

    input >> val;                        // Input a binary number
                                         // Can use std::cin or another stream
    std::cout << val.to_ulong() << "\n";
    std::cout << val[5] << "\n";
}

If you don't have boost use the std::bitset.
The only problem with std::bitset it has a fixed size

#include <bitset>
#include <sstream>
#include <iostream>

int main()
{
    std::bitset<16>             val;     // fixed 16 bit size

    std::cout << "Enter binary number:\n";   
    std::cin >> val;                        // Input a binary number
                                         // Can use std::cin or another stream
    std::cout << val.to_ulong() << "\n";
    std::cout << val[5] << "\n";
}

4 Comments

@Junior89: Then you are doing something wrong. Can you be a bit more specific? Note: It uses boost (which is one of the things as a C++ program you install immediately after the compiler). If you don't have boost or have not set the include path to pick up boost then it will fail to compile.
yes the errors were about the boost, but thanks for the new code you edit it works good. The only thing is that you gave an input "1010101010" how can I input my own binary number like --> cout << "Enter binary number: "; cin >> input;
Thanks I did that, but now when I enter a higher binary number such as 100100 (36) the correct output is wrong, like for example I std::cout << val[5] comes out to be 1 instead of a 0, and if I did val[4] I get a 0 instead of a 1
@Junior89: You are think backwards. If you input a decimal number "36" then myInt[0] == 6 and myInt[1] == 3. If you input a binary number the same rule applies: "100" val[0] == 0 && val[1] == 0 && val[2] == 1. The higher more significant bits are going to be higher in the array. You want the binary number to behave like other numbers (not like a string).
0

STORING A BINARY NUMBER INTO AN ARRAY


char binaryArray [5]; // The array looks like this: [][][][][]

cout << "Enter binary number: ";
cin >> binaryArray; // Stores the binary number into the array: [1][0][1][0][0]

cout << binaryArray[0] << endl; // The first element is sent to standard output.
cout << binaryArray[1] << endl; // The second element is sent to standard output.

For your input the output will be:

1
0

Here we have an array of characters. We input the binary number into the array and then we print each element of the array to display each bit. The first print line accesses the first element [1] [0] [1] [0] [0]. The second print line accesses the second element [1] [0] [1] [0] [0].

Let's say we had a binary number with 100 characters. The way that we output each element of the array would take a long time.

1.) Can you think of a more efficient way of printing out the contents of our array?

2.) How can we ensure that the user is inputting only ones and/or zeroes?

2 Comments

hey thanks a lot for the code it really helped, but this is for the beginning of my program, its to get me started. What my program has to do is to read the input binary number, then for each 1 c1++ cout that number return it, vice versa for 0 except c0++ rand(1, c1). what am I trying to do is to output the "states" because from the binary input I am going to show the states. so for example with your binary number of 100, it would be invalid since there are more 0s than 1s+1. if I input 10100, the output would be 1,2,rand(1,c1), 3, rand(1,c1), rand(1,c1). get what I have to do? lol
wait 100 wont be invalid, sorry

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.