2014-09-23 80 views
-2
// program that split a string and stock words in a vector array 

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

int main() 
{ 
cout << "substring using vector test\n" << endl; 

bool reste(1); 
vector<string> mots; // our vector 'word' mots is french vector 
size_t found(-1);  // init at - 1 because i need to wirte +1 to start at 0 
int prevFound(-1);  // same explanation, prevFound meaning previous found 
string chaine ("let's test this piece of code"); 

do 
{ 
found = chaine.find(" ",found+1); // looking for the first space encountered 


if (found!=string::npos) // if a space is found.. 
{ 
    cout << "\nSpace found at: " << found << '\n'; // position of the first space 
    mots.push_back(chaine.substr(prevFound+1,found-prevFound)); // add a 'case' in vector and substract the word // 
    prevFound = found; // stock the actual pos in the previous for the next loop 


} 
if (found==string::npos) // if no space is remaining, extract last word 
{ 
    cout << "\nlast word\n\n" << endl; 
    mots.push_back(chaine.substr(prevFound+1,found-prevFound)); 
    reste = 0; 
} 

}while (reste); 


cout << "\nraw sentence : " << chaine << endl; 

unsigned int taille = mots.size(); // taille meaning size 
cout << "number of words" << taille << "\n" << endl; 

for (int i(0); i<=taille; i++) // loop showing the extracted words 
{ 
cout << mots[i] << '\n'; 
} 
return 0; 
} 

感謝您的時間。 我試圖翻譯我的母語代碼中的大部分代碼,我可能在我的外語上是無用的。 我已經在網上學習了兩個星期的C++,現在是clement。我的代碼編譯,執行但程序崩潰到底

我只想知道爲什麼我的代碼編譯和執行,但最終崩潰,我的代碼與靜態arry很好。 也許我需要一個集裝箱? 如果是的話,有人可以糾正我的代碼與std :: set。 在此先感謝。

+1

你最後的循環遍歷一個太多的指標,所以你訪問'mots'越界。 – juanchopanza 2014-09-23 21:10:34

+0

因爲「npos是一個靜態成員常量值,對於size_t類型的元素來說,它的最大可能值」在if(found == string :: npos)found-prevFound的結果中以substr長度的大nr參數 – 2014-09-23 21:20:24

回答

2

你的程序有未定義的行爲,因爲你訪問你的向量越界

更改此:

for (int i(0); i<=taille; i++) 

要:

for (int i(0); i<taille; i++) 

或者更簡單地說:

for (auto& mot : mots) 
{ 
    cout << mot << '\n'; 
} 
+0

非常感謝。你能解釋一下for(auto&mot:mots) – 2014-09-23 21:37:10

+0

它是一個範圍循環:參見[here](http://en.cppreference.com/w/cpp/language/range-for) – quantdev 2014-09-23 21:44:29