Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...