我的代码编译,执行但程序崩溃到底
问题描述:
// 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。 在此先感谢。
答
你的程序有未定义的行为,因为你访问你的向量越界。
更改此:
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
你最后的循环遍历一个太多的指标,所以你访问'mots'越界。 – juanchopanza 2014-09-23 21:10:34
因为“npos是一个静态成员常量值,对于size_t类型的元素来说,它的最大可能值”在if(found == string :: npos)found-prevFound的结果中以substr长度的大nr参数 – 2014-09-23 21:20:24