2013-12-11 40 views
-1

所以我調試我得到一個運行時錯誤。 「字符串下標超出範圍」。串標越界C++:調試

我知道問題出在哪裏以及是什麼原因造成的,但我希望能夠找到一個類似或相同的方式不給我的錯誤執行可能的解決方案。

下面是代碼片段來發生錯誤。糾正我,如果我錯了,問題發生,因爲我聲明一個0長度的字符串,然後試圖操縱第n個元素。

std::string VsuShapeLine::GetRunwayNumber() 
{ 
    std::string name, nbstr, newnbstr, convnbstr; 
    int idx,idx2, num, count, pos; 
    char buf[3]; 
    int idx3=-1; 
    name = this->GetName(); 
    idx = name.find("ALight"); 
    if (idx == -1) 
    { 
     idx = name.find("Lights"); 
     idx3 = name.find_last_of("Lights"); 
    } 
    idx2 = name.find('_'); 
    idx2 +=3; 

    nbstr = name.substr(idx2, idx-idx2); 

    if (idx3 != -1) 
     idx3++; 
    else 
     idx3 = idx+6; 

    if (name.at(idx3) == 'N') 
    { 
     pos = nbstr.length(); 
     if (isalpha(nbstr[idx-1])) 
      nbstr[pos-1] = _toupper(nbstr[pos-1]); 
     return (nbstr); 
    } 

    else if (name.at(idx3) == 'F') 
    { 
     convnbstr = nbstr.substr(0,2); 
     num = atoi(convnbstr.data()); 
     num +=18; 
     _itoa(num, buf, 10); 
     newnbstr = buf; 
     count = nbstr.size(); 

     if (count > 2) 
     { 
      if (nbstr.at(2) == 'l' || nbstr.at(2) == 'L') 
       newnbstr += 'r'; 

      else if (nbstr.at(2) == 'r'|| nbstr.at(2) == 'R') 
       newnbstr += 'l'; 

      else if (nbstr.at(2) == 'c' || nbstr.at(2) == 'C') 
       newnbstr += 'c'; 
     } 
     pos = newnbstr.length(); 
     if (isalpha(newnbstr[pos-1])) 
      newnbstr[pos-1] = _toupper(newnbstr[pos-1]); 
     return (newnbstr); 
    } 

    return (""); 
} 
+1

也許你能告訴我們什麼'idx'設置爲,因爲這似乎是你的問題。 –

+0

如果這是你的整個代碼,並且字符串確實是空的,你不能索引它。 –

+0

你....做任何事'nbstr'在宣佈它並試圖以索引到它之間?如果'pos'爲0,那麼當然'nbstr [pos-1]'會使運行時適合並開始。 –

回答

0

順便說一句對任何有興趣的問題是在這條線:

if (isalpha(nbstr[idx-1]) 

此時nbstr的長度是3和IDX」值的字符串,我的程序的工作方式,始終爲9或10

同樣如不再更新忍提到的檢查應使用字符串::找到函數之後進行。