使用find和substr函数进行解析

时间:2013-09-16 16:59:43

标签: c++ tokenize

运行此代码时出现内存问题:

#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来获取一个新的字符串来获取位,从逗号后面取整行。我遇到了分段错误。

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

vector<string> tokens;

声明标记向量,默认大小为(0)。您正在使用operator[]而不是push_backemplace_back向其添加项目,因此它正在访问未分配的内存。您需要调整数组的大小:

tokens.resize(10);

或使用push_back / emplace_back进行插入:

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

答案 2 :(得分: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;