我的代码编译,执行,但程序最后崩溃
My code compile, execute but program crashes at the end
// 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';
}
相关文章:
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 我的C++程序只写入文本文件最后一个条目
- 程序应该显示文件的最后5行,但它不适用于大文件
- C++ 链表程序打印最后一个数据项 n 次
- 为什么两个程序中的总和值在最后不同?
- 以下递归程序的最后一行是如何工作的
- 如何在应用程序进行大量printf时,在固定输入的终端中设置最后一行
- C++程序在迭代到数组的最后一个元素时崩溃
- 当该应用程序中加速文件的最后一个修改时间发生更改时,如何重新启动应用程序
- 试图删除最后一个std ::向量元素时,程序会崩溃
- 合并排序程序总是有效的,但有时会在最后说中止陷阱
- 为什么当我在Visual c ++ studio 2010中运行应用程序时光标会转到最后一个文本框
- 最后挂接一个程序
- 当我采用测试用例数 = 1 时,我的程序终止.其他明智的是,它给出了正确的答案,但跳过了最后一个测试用例
- 我在一个简单控制台程序(c++)中的第一列代码最终成为我的最后一列
- 使Qt应用程序在最后一个窗口关闭时不退出
- 调用函数后,程序不会运行到最后
- 为什么我的程序最后崩溃了
- 我的代码编译,执行,但程序最后崩溃
- msxml程序最后一行出错