// 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;
}
感谢您的时间。 我试图翻译用我的母语编码的大部分代码,我可能在我的expalanations上无关紧要。 我现在已经在网上学习了两个星期的c ++,非常好。
我只是想知道为什么我的代码编译和执行但最后崩溃,我的代码用静态arry做得很好。 也许我需要一个集装箱? 如果是,有人可以使用std :: set更正我的代码。 提前谢谢。
答案 0 :(得分:3)
您的程序有未定义的行为,因为您访问了矢量越界。
改变这个:
for (int i(0); i<=taille; i++)
致:
for (int i(0); i<taille; i++)
或更简单:
for (auto& mot : mots)
{
cout << mot << '\n';
}