1

給定一個全局矢量的ASCII代碼和相應的數字值和一個字符串list,像000.00-000.0.0.0,該功能需要一個input令牌字符串2炭或3個字元長和具有單ASCII符號替換它表示0到184之間的數字值,然後返回不帶刪除符的縮短字符串,如out。另外,在反向(方向1)給定ASCII符號時,它將轉換回數字字符串並返回。遞歸函數具有out_of_range例外

//looks for input string in vector and returns output, 'c' is check row, 'r' is return row 
string vectorSearch(string &check, int n, int c, int r) 
{ 
    if (check.length() <= 1) 
     return check; 
    if (list[n][c] == check || list[n][c] == ('0'+check)) //adds leading zero if 2char long 
     return list[n][r]; 
    else 
     return vectorSearch (check, ++n, c, r); 
} 

//this function takes an ontology and either changes from single char 
//to string or takes strings and converts to char representation 
string Lexicon::convertOntology(string input, int direction, string out, string temp) 
{ 
    if (input == "" && temp == "") 
     return out; //check for completed conversion 
    else { 
     if (input[0] == '.' || input[0] == '-' || input == "") { //found deliniator or endk 
      if (input != "") return convertOntology(input.substr(1),direction, 
       out+=vectorSearch(temp, 0, direction, 1-direction), ""); 
      else return convertOntology("", direction, 
       out+=vectorSearch(temp, 0, direction, 1-direction), ""); 
     } else 
      return convertOntology(input.substr(1), direction, out, temp+=input[0]); //increment and check 
    } 
} 

這些函數在解析最後一個字符後的輸出上工作正常。在線return convertOntology(input.substr(1), direction, out+=add, temp);中斷時,input == ""temp == "0" - 最後通過vectorSearch()應該清除temp並將temp字符添加到out字符串中,因爲temp爲== 1char,因此應該從vectorSearch()返回爲它是。然後清除inputtemp == ""convertOntology()退貨支票。但是,它從來沒有達到上vectorSearch()第一線休息,有一個

Unhandled exception at 0x77bc15de exception: std::out_of_range at memory location 0x0035cf1c 

這是怎麼回事?這是通過返回遞歸回溯的問題,我錯過了某處返回以打破遞歸循環?

+0

我可能已經找到它了;在最後一輪input.substr(1)在字符串上調用「」 – 2012-07-26 15:16:29

回答

2

對於temp == ""input != ""的情況,您可以撥打input.substr(1),這很好,超出範圍。當input字符串是一個字符長

1

即使你沒有得到else部分,

input.substr(1) 

會拋出異常。

似乎它不 - input.substr(input.size())被允許,並返回一個空字符串。


您稍後可能會在VectorSearch中遇到類似問題。如果沒有匹配,你將增加n,直到它超出範圍。

+0

捕獲不匹配的情況 - 這是爲下一個版本保存的功能。我將用1個字符來測試input.substr(1),在第一輪中似乎沒有問題。 – 2012-07-26 15:29:38

+0

我加了這個修補程序'if(check.length()<= 1 || n > 200)' – 2012-07-26 15:35:13

+0

是的,我錯了 - 它確實沒問題。按照我的假設,'substr(pos)'中'pos'的要求是'pos <= size()',而不是'pos 2012-07-26 15:38:29