2012-06-18 51 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; 
    } 
} 
相關問題