comparing a string at index i to a value in C++

  c++, string, string-comparison

So im working on a class assignment where I need to take a base 2 binary number and convert it to its base 10 equivalent. I wanted to store the binary as a string, then scan the string and skip the 0s, and at 1s add 2^i. Im not able to compare the string at index i to ‘0, and im not sure why if(binaryNumber.at(i) == ‘0’) isnt working. It results in an "out of range memory error". Can someone help me understand why this doesnt work?

#include <iostream>
using namespace std;

void main() {
    string binaryNumber;
    int adder;
    int total = 0;

    cout << "Enter a binary number to convert to decimal n";
    cin >> binaryNumber;
    reverse(binaryNumber.begin(),binaryNumber.end());

    for (int i = 1; i <= binaryNumber.length(); i++) {
        if(binaryNumber.at(i) == '0') { //THIS IS THE PROBLEM
        //do nothing and skip to next number
        }
        else {
            adder = pow(2, i);
            total = adder + total;
        }
    }

    cout << "The binary number " << binaryNumber << " is " << total << " in decimal form.n";
    system("pause");
}

Source: Windows Questions C++

LEAVE A COMMENT