0

I have a file that contains different columns in different lines. For example

10 20 30 60 
60 20 90 100 40 80
20 50 60 30 90
....

I want to read the last three numbers in each row. So the output will be

20 30 60 
100 40 80
60 30 90

I can not use the following structures because of variable size in each line

structure 1:

std::ifstream fin ("data.txt");
while (fin >> a >> b >> c) {...}

structure 2:

string line;
stringstream ss;
getline(fin, line);
ss << line;
int x, y, z;
ss >> x >> y >> z >> line;

What should I do then?

mahmood
  • 23,197
  • 49
  • 147
  • 242

1 Answers1

1

Read them into a std::vector and lop off everything but the last 3 items.

std::string line;
while (getline(fin, line))
{
    std::vector<int> vLine;
    istringstream iss(line);
    std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::back_inserter(vLine));
    if (vLine.size() > 3)
    {
        vLine.erase(vLine.begin(), vLine.begin() + (vLine.size() - 3));
    }
    // store vLine somewhere useful
}
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • I have to first tokenize the line and the problem is, I don't know the exact number of tokens in each line – mahmood Oct 01 '13 at 19:31