0

Trying to tokenize a String in C++ which is read from a file, separated by commas, but I only need the first 3 data of every line.

For example: The lines look like this:
140,152,2240,1,0,3:0:0:0:
156,72,2691,1,0,1:0:0:0:
356,72,3593,1,0,1:0:0:0:

But I only need the first 3 data of these lines. In this case:
140, 152, 2240
156, 72, 2691
356, 72, 3593

I'm trying to add these data into a vector I just don't know how to skip reading a line from the file after the first 3 data.

This is my current code: (canPrint is true by default)

ifstream ifs;
        ifs.open("E:\\sample.txt");
        if (!ifs)
            cout << "Error reading file\n";
        else
            cout << "File loaded\n";



        int numlines = 0;
        int counter = 0;
        string tmp;

        while (getline(ifs, tmp))
        {
            //getline(ifs, tmp); // Saves the line in tmp.
            if (canPrint)
            {
                //getline(ifs, tmp);
                numlines++;

                // cout << tmp << endl; // Prints our tmp.
                vector<string> strings;
                vector<customdata> datalist;
                istringstream f(tmp);
                string s;
                while (getline(f, s, ',')) {
                    cout << s << " ";
                    strings.push_back(s);
                }
                cout << "\n";


            }

1 Answer 1

1

How about checking the size of the vector first? Perhaps something like

while (strings.size() < 3 && getline(f, s, ',')) { ... }

Not the answer you're looking for? Browse other questions tagged or ask your own question.