【问题标题】:My code compile, execute but program crashes at the end [closed]我的代码编译,执行,但最后程序崩溃[关闭]
【发布时间】:2014-11-18 05:29:42
【问题描述】:
// 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++ 两个星期了,请原谅。

我只是想知道为什么我的代码编译和执行但最后崩溃了,我的代码在静态数组中运行良好。 也许我需要一个固定的容器? 如果是,有人可以用 std::set 更正我的代码吗? 提前致谢。

【问题讨论】:

  • 你的最后一个循环循环了一个太多的索引,所以你访问mots越界了。
  • 因为在 if (found==string::npos) found-prevFound 的情况下,“npos 是一个静态成员常量值,对于 size_t 类型的元素具有最大可能值”对于 substr 的长度参数到 big nr

标签: c++ string vector split substring


【解决方案1】:

您的程序具有未定义的行为,因为您访问了您的向量超出范围。

改变这个:

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

收件人:

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

或者更简单:

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

【讨论】:

  • 非常感谢。你能解释一下 for (auto& mot : mots)
  • 这是一个for range 循环:见here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
相关资源
最近更新 更多