boost tokenizer的随机行为

时间:2012-06-10 23:26:32

标签: c++ boost boost-tokenizer

我遇到了boost tokenizer的问题,这是我的代码:

#include <iostream>
#include <vector>
#include <boost/tokenizer.hpp>

using namespace std;

static vector<std::string> tokenize(const std::string& input, const char delim) {
    std::cout << "Tokenize: " << input << std::endl;
    vector<std::string> vector;
    typedef boost::char_separator<char> TokenizerSeparator;
    typedef boost::tokenizer<TokenizerSeparator> Tokenizer;
    TokenizerSeparator separator(&delim);
    Tokenizer tokenizer(input, separator);
    Tokenizer::iterator iterator;

    for(iterator=tokenizer.begin(); iterator!=tokenizer.end();++iterator){
        std::cout << "elem found: " + *iterator << std::endl;
        vector.push_back(*iterator);
    }
    return vector;
}

int main(int argc, const char * argv[])
{
    string input = "somedata,somedata,somedata-somedata;more data;more data";
    vector<string> list = tokenize(input, ';');

    return 0;
}

此代码始终不一致。有时它可以工作,有时不运行多次。当它不起作用时,我得到一个输出:

Tokenize: somedata,somedata,somedata-somedata;more data;more data
elem found: some
elem found: ata,some
elem found: ata,some
elem found: ata-some
elem found: ata
elem found: more 
elem found: ata
elem found: more 
elem found: ata

我做错了什么?

感谢。

2 个答案:

答案 0 :(得分:3)

TokenizerSeparator separator(&delim);

您根据存储的字符地址而不是字符的值进行标记。

答案 1 :(得分:0)

感谢@DavidSchwartz的回答(见上面的评论)。

char_separator在其构造函数中需要一个有效的C字符串。

相关问题