Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store an input into an array? C++

Tags:

c++

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.

like image 494
Junior89 Avatar asked Dec 16 '22 11:12

Junior89


1 Answers

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.

like image 102
Pablo Avatar answered Jan 11 '23 20:01

Pablo