2012-06-18 129 views
0

试图将二进制输入字符串转换为整数的向量。我想这样做而不使用内置的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循环来寻找下标变得太大,但没有太多运气的地方。

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

+1

不断言告诉你哪一行错误发生呢?如果你有这些信息,你为什么要保密?这是谜题中最重要的一部分。 –

+0

如果你不反对使用C函数,你可以检查'strtol'。 –

回答

1

操作数是错误的顺序:

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

变化:

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

同为以下if声明。第二个操作数只在第一个操作数为true时才被评估,以防止出界限访问。

+0

优秀,我没有考虑条件的顺序。谢谢!它现在打印并存储所有输入的数字,但仍然打印出相同的错误。 – NicholasNickleby

+0

@NicholasNickleby,你是否也改变了'if'操作数的顺序? – hmjd

0

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

See it here

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