2013-09-16 110 views
0

我这段代码运行时得到一个内存问题解析:与查找和SUBSTR功能

#include <iomanip> 
#include <string> 
#include <iostream> 
#include <vector> 

using namespace std; 

int main(){ 
     vector<string> tokens; 
     int x,y; 
     string toParse = "word,more words,an int 5,some more,this is the 5th one,thisll be 6,seven,eight,nine,tenth,extra"; 
     for(y=0; y<10; y++){ 
      cout << "in for loop " << y << endl; 
      x = toParse.find(","); 
      tokens[y]= toParse.substr(0,x); 
      toParse = toParse.substr(x+1); 
     } 
     for(y=0; y<9; y++) 
      cout << tokens[y] << endl; 
} 

从本质上讲,我只是想存储的值,取决于逗号分隔。

x应该设置为逗号的位置,我将这些信息存储在逗号之前。然后,我使用substr来获取一个新的字符串来获取位,从逗号后面取整行。我遇到了分段错误。

回答

1

替代tokens[y]=toParse.substr(0, x)

tokens.push_back(toParse.substr(0, x));

for(y=0; y<10; y++){ 
     cout << "in for loop " << y << endl; 
     x = toParse.find(","); 
     tokens.push_back(toParse.substr(0,x)); 
     toParse = toParse.substr(x+1); 
    } 
    for(y=0; y<9; y++) 
     cout << tokens[y] << endl; 
1

这是因为您使用tokens[y]没有足够的项目在向量中。您需要使用tokens.push_back(...)代替,或用十个项目申报向量:

std::vector<std::string> tokens(10); 
1
vector<string> tokens; 

声明令牌载体,以默认大小(0)。然后使用operator[]而不是push_backemplace_back向其添加项目,因此它正在访问未分配的内存。您可能需要您的大小排列:

tokens.resize(10); 

或者使用push_back/emplace_back做插件:

tokens.push_back(toParse.substr(0, x));