Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

c++ - populating a string vector with tab delimited text

I'm very new to C++.

I'm trying to populate a vector with elements from a tab delimited file. What is the easiest way to do that?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There could be many ways to do it, simple Google search give you a solution.

Here is example from one of my projects. It uses getline and read comma separated file (CSV), I let you change it for reading tab delimited file.

ifstream fin(filename.c_str());
string buffer;

while(!fin.eof() && getline(fin, buffer))
{
    size_t prev_pos = 0, curr_pos = 0;
    vector<string> tokenlist;
    string token; 
    // check string
    assert(buffer.length() != 0);

    // tokenize string buffer.
    curr_pos = buffer.find(',', prev_pos);

    while(1) {

        if(curr_pos == string::npos)
            curr_pos = buffer.length();

        // could be zero
        int token_length = curr_pos-prev_pos;

        // create new token and add it to tokenlist.
        token = buffer.substr(prev_pos, token_length);
        tokenlist.push_back(token);

        // reached end of the line
        if(curr_pos == buffer.length())
            break;

        prev_pos = curr_pos+1;
        curr_pos = buffer.find(',', prev_pos);
    }
}

UPDATE: Improved while condition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...