我的代码编译,执行,但程序最后崩溃

My code compile, execute but program crashes at the end

本文关键字:程序 最后 崩溃 执行 代码 编译 我的      更新时间:2023-10-16
// 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 testn" << 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 wordnn" << 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 ++两个星期了,克莱门特。

我只想知道为什么我的代码编译和执行但最后崩溃,我的代码在静态arry上做得很好。也许我需要一个套装容器?如果是,有人可以用 std::set 更正我的代码吗?提前谢谢。

您的程序具有未定义的行为,因为您越访问向量。

更改此内容:

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

自:

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

或者更简单地说:

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