-3

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.

Fredrick Chow
  • 37
  • 1
  • 1
  • 2
  • 2
    Ask yourself a simple question. If the string has `N` characters, and you want the `I`th character from the end of the string, what is the mathematical formula to compute the index of that character, from the beginning of the string? – Sam Varshavchik Sep 22 '16 at 00:22
  • STL-wise, have you heard of [`std::bitset`](http://en.cppreference.com/w/cpp/utility/bitset)? Check and see whether it will be useful. And please do get yourself a [good C++ text](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – WhiZTiM Sep 22 '16 at 00:23

1 Answers1

1

You can do this:

#include <iostream>
#include <string>

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

}
Onep
  • 16
  • 5