Search code examples
c++stringstring-comparison

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


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");
}

Solution

  • Array indices for C++ and many other languages use zero based index. That means for array of size 5, index ranges from 0 to 4. In your code your are iterating from 1 to array_length. Use: for (int i = 0; i < binaryNumber.length(); i++)