NicholasNickleby
NicholasNickleby

Reputation: 29

Binary String Converted to Integers

Trying to convert a string of binary inputs into a vector of ints. I'd like to do this without using a built-in C++ function. Here is a snippet of the code and the execution errors (compiles fine).

Example Input: "1011 1001 1101"

Should be stored in vector as ints 11,9, and 13

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()  
{
    string code,key;
    vector<int>digcode;
    vector<int>ans;
    cout<<"Enter binary code:\n";
    getline(cin,code);
    cout<<"Enter secret key:\n";
    cin>>key;

    for(int i=0;i<code.length();)
    {
        int j=2, num=0;
        while (code[i]!=' '&&i<code.length())
        {
        num*=j;
        if (code[i]=='1')
        num+=1;
            i++;
        }
        cout<<num<<" ";
        digcode.push_back(num);
        if(code[i]==' '&&i<code.length())
            i++;
    }
}

ERROR MESSAGE: "Debug Assertion Failed!" "Expression: string subscript out of range"

All but the last number are printed and stored. I've traced through the for and while loops looking for where the subscript gets too large, but haven't had much luck.

Any help is appreciated! Thanks.

Upvotes: 0

Views: 716

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 476940

Your code could be simplified a fair bit:

for (std::string line; ; )
{
    std::cout << "Enter a line: ";
    if (!std::getline(std::cin, line)) { break; }

    for (std::string::const_iterator it = line.begin(); it != line.end(); )
    {
        unsigned int n = 0;
        for ( ; it != line.end() && *it == ' '; ++it) { }
        // maybe check that *it is one of { '0', '1', ' ' }

        for ( ; it != line.end() && *it != ' '; ++it) { n *= 2; n += (*it - '0'); }
        std::cout << "   Read one number: " << n << std::endl;
    }
}

Upvotes: 0

corn3lius
corn3lius

Reputation: 4985

After you parse the digits by space? There is the strtol() function that you can supply a base conversion to and get the integer value.

See it here

Upvotes: 0

hmjd
hmjd

Reputation: 121961

The operands are in the wrong order:

while (code[i]!=' '&&i<code.length())

change to:

while (i < code.length() && code[i]!=' ')

Same for following if statement. The second operand will only be evaluated if the first operand is true, preventing out of bounds access.

Upvotes: 1

Related Questions