Fredrick Chow Fredrick Chow - 2 months ago 19
C++ Question

Count bits starting from the ones, then tens and so on

Coding in C++.

I'm trying to print out only a specified digit from a binary code in the form of a string. The user can specify a certain digit position, and the number in that position must be printed.

Eg. string c = "11011001" and the user wants the 1st position. The output has to be 0.

Count indices start at 0 and from the 'ones' digit meaning a request of the 1st position is the number in the 'tens' digit position.

I have no idea how to start counting from the ones column. I tried c.at() but that starts from the left most digit and counts towards the right.

Answer

You can do this:

#include <iostream>
#include <string>

int main ()
{
  std::string str ("11011001");
  int postion = 1;
  std::cout << str[str.length()-position];

}