二进制字符串转换为整数

Binary String Converted to Integers

本文关键字:整数 转换 字符串 二进制      更新时间:2023-10-16

尝试将一串二进制输入转换为整数向量。我想在不使用内置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 循环寻找下标太大的地方,但没有太多运气。

任何帮助不胜感激!谢谢。

操作数顺序错误:

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

更改为:

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

以下if语句相同。仅当第一个操作数为 true 时,才会计算第二个操作数,从而防止越界访问。

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

在这里看到它

你的代码可以简化一点:

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