二进制字符串转换为整数

时间:2012-06-18 20:59:35

标签: c++ indexing

尝试将一串二进制输入转换为int的向量。我想在不使用内置C ++函数的情况下执行此操作。这是代码片段和执行错误(编译好)。

示例输入:“1011 1001 1101”

应该以向量11,9和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++;
    }
}

错误消息:“调试断言失败!” “表达式:字符串下标超出范围”

打印并存储除最后一个号码之外的所有号码。我已经遍历了for和while循环,寻找下标变得太大的地方,但没有多少运气。

任何帮助表示赞赏!感谢。

3 个答案:

答案 0 :(得分:1)

操作数的顺序错误:

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

更改为:

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

跟随if语句相同。仅当第一个操作数为真时才会计算第二个操作数,从而防止超出边界访问。

答案 1 :(得分:0)

用空格解析数字后? 有strtol()函数可以提供基本转换并获取整数值。

See it here

答案 2 :(得分:0)

您的代码可以简化一下:

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;
    }
}
相关问题