2015-08-31 24 views
2

我有字符串矢量:的std :: string :: SUBSTR拋出的std :: out_of_range但自變量是在極限

vector<string> tokenTotals; 

push_back被調用時,長度41的字符串被存儲和我必須操作我的向量中的每個元素,並獲得兩子,先在範圍爲0〜28,第二次在範圍29〜36:

for(int i = 0; i < tokenTotals.size(); i++) 
{ 
    size_t pos = tokenTotals[i].find(": "); 
    cout << tokenTotals[i] << endl; // Show all strings - OK 
    cout << tokenTotals[i].length() << endl; // Lenght: 41 
    string first = tokenTotals[i].substr(0, 28); // OK 
    string second = tokenTotals[i].substr(29, 36); // ERROR 
    cout << first << " * " << second << endl; 
} 

但是,當我試圖讓第二子,我得到以下錯誤:

terminate called after throwing an instance of std::out_of_range. 
what():: basic_string::substr 

有什麼想法會發生什麼?

回答

11

查看std::string::substr reference。第二個參數是子字符串長度不是子字符串後面字符的位置,所以結果是嘗試訪問元素超出範圍 - std::out_of_range被拋出。

隨着tokenTotals[i].substr(0, 28)這個錯誤並不明顯,因爲子既有大小和位置的一個過去端28

7
substr(29,36); 

將嘗試獲得始於29位,並具有大小的字符串由36個字符組成的。不幸的是,29 + 36> 41

documentation

相關問題