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.
The operands are in the wrong order:
change to:
Same for following
ifstatement. The second operand will only be evaluated if the first operand is true, preventing out of bounds access.