2011-11-21 50 views
0

我認爲這個錯誤與我的字符串太大有關。如果該功能正常工作,我懷疑我會接近最大字符串大小(除非真的是這個問題?我懷疑它是因爲這是用於硬件分配,我們需要返回output與歌詞)。什麼是拋出這個錯誤?字符串有多大?C++中的字符串類有多大?

錯誤:

terminate called after throwing an instance of 'std::length_error' 
what(): basic_string::_S_create 
Aborted (core dumped) 

職能:list[]

string generateSong(string list[], int num) 
{ 
    string output; 

    for(int count = 0; count <= num; count++) 
     output += list[count] + " bone connected to the " 
     + list[count + 1] + " bone\n"; 

    return output; 
} 

內容:

string list[9] = 
    { 
     "toe", 
     "foot", 
     "leg", 
     "knee", 
     "hip", 
     "back", 
     "neck", 
     "jaw", 
     "head" 
    }; 

num是9.是output真的變得太大了?一切都很好(使用g ++)。

+0

是否'名單[]'有11款產品? –

+0

'list []'包含9個項目。我會把這些項目放在OP中。 –

+0

迭代至count Pramod

回答

4

與您的代碼的實際問題是在這裏:

for(int count = 0; count <= num; count++) 
        // ^^^ problem! 

應該count < (num-1),因爲你在循環體使用list[count + 1]

+0

作出你建議的更改,但沒有骰子。仍然得到相同的錯誤。 –

+0

@Eegabooga:對不起。它應該是'count <(num-1)'。 – Nawaz

+0

啊! 'count <(num-1)'解決了問題!非常感謝。我應該記得'list [9]'將會是數組中的第10項。 Woops –

0

std::string的最大尺寸被定義爲我的max_size()函數。

試試這個:

std::string s; 
std::cout << s.max_size(); 
+0

我得到了4611686018427387897.所以我應該沒有關係.. –

3

正如你所訪問list[count + 1],你只能迭代從0到NUM - 1