Home > Back-end >  comparing a string at index i to a value in C
comparing a string at index i to a value in C

Time:09-21

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

CodePudding user response:

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 )

CodePudding user response:

Because your started from 1 and not 0

for (int i = 1; i <= binaryNumber.length(); i  )

Try with that

for (int i = 0; i < binaryNumber.length(); i  )

CodePudding user response:

The problem is not with the if statement but with your loop condition and index.

You have your index begin at one, while the first character of a string will be at index zero. Your out memory range error is caused by the fact that the loop stops when less than or equal, causing the index to increase one too many and leave the memory range of the string.

Simply changing the loop from

for (int i = 1; i <= binaryNumber.length(); i  ) {
    if(binaryNumber.at(i) == '0') {
    }
    else {
        adder = pow(2, i);
        total = adder   total;
    }
}

To

for (int i = 0; i < binaryNumber.length(); i  ) {
    if(binaryNumber.at(i) == '0') { 
    }
    else {
        adder = pow(2, i);
        total = adder   total;
    }
}

Will solve the issue.

  • Related