二进制字符串转换为整数
Binary String Converted to Integers
尝试将一串二进制输入转换为整数向量。我想在不使用内置C++函数的情况下执行此操作。这是代码和执行错误的片段(编译正常)。
示例输入:"1011 10011101"
应以整数 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;
}
}
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 如何在C++中将整数转换为其数字数组
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 将最小值整数转换为无符号长整型
- 为什么我们不能将使用异或运算找到的整数转换为字符?
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 将74位整数转换为以31为底的整数
- 独立于实现的浮点/整数转换
- 以最少的步骤将给定整数转换为另一个整数
- 浮点到整数转换出错(即使浮点数已经是整数)
- 了解双精度转换与整数转换中的整数与截断关系
- 禁止具有精度损失的整数转换
- 将任意整数转换为 void*
- 将 32 位大端有符号整数转换为有符号小端整数
- char a[0] 使用 itoa() 将整数转换为字符串的目的
- 使用函数时从整数转换为字符串
- 尝试从整数转换为字符串的月份
- 如何在C++中将整数转换为字节,以便 Unity 在通过 UDP 传输后能够理解它们
- 如何将 Q 格式的整数转换为浮点数(反之亦然)
- 如何避免字符串到整数转换情况下的无效参数异常