Putting elements of String into an Array

I'm prompting for input in the form of a binary number and i need to be able to deal with that input one bit at a time, easiest way I know of doing this is to put the data in an array.

But how? Or perhaps I'm over-thinking this problem and there's a better solution? I'm all ears.
one way that springs to mind:

1) prompt the user to enter a binary number of x length and store it in a string.
1
2
3
string sGivenBinary = "";
cout<<"You elicitation string here!" <<endl;
cin>>sGivenBinary;


2) check it to ensure every character is either a 0 or a 1.
1
2
3
4
5
6
for(int i = 0; i < sGivenBinary.size(); i++)
{
    char cCurrent = sGivenBinary.at(i);

    //your checking routine here
}


Then you can convert the string, into integers one character at a time with your favorite conversion routine.

You will probably want to wrap the given code in a do loop, incase the user inputs invalid data.

I hope this helps!
Last edited on
1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
    #include <stdlib.h>
     
    int main ()
    {
      char binary[10] = "101010101", *end;
      long x = strtol(binary, &end, 2);
      printf("%s in base 2 = %ld in base 10\n", binary, x);
      return 0;
    }


Output:
101010101 in base 2 = 341 in base 10

Source: http://www.codecogs.com/reference/c/stdlib.h/strtol.php

Perhaps this isn't what you seek, while you mention "I need to be able to deal with that input one bit at a time", which is not the case here.
Last edited on
Topic archived. No new replies allowed.