Reputation: 11
My data looks like:
12 32 21 42
33 566 332 12
66 994 4 33
12 33 33 41
and I want to push the first three values on an vector of integers while ignoring the last value. Every line I need to have a new vector of the first 3 numbers in there. Just spaces are used as separators (a TAB). thanks!
Upvotes: 0
Views: 750
Reputation: 58667
std::getline()
std::istringstream
to parse the integers outNotice what happened here: You wrote a question, I translated it into a sequence of instructions, and finally you translate that into code. That's how we write simple programs. The trick is in understanding the question well enough to translate it into pseudocode as above.
Upvotes: 1
Reputation: 53289
Well, ultimately you want to end up with an std::vector<int>
of 3 integers for each line in the text file. This is basically an exercise in parsing the file, which is very easy to do using a C++ file stream object along with a stream input iterator.
Use an std::ifstream
object to open the file. You can then iterate over each integer in the file using an std::istream_iterator<int>
. This will extract each integer, so you can store it in a vector. If you want to discard the fourth integer on each line, just keep a counter variable handy so that you can discard every 4th value.
And that's basically it. I'll leave it to you to actually produce the code.
Upvotes: 1
Reputation: 15872
std::ifstream
will work if you are just reading the file directly. If you are using getline
(which really isn't necessary here), you can write a simple split function to separate the values and insert the ones you want. Since this sounds like schoolwork, I doubt you'll want to use the boost::
methods that would make this rather trivial.
Upvotes: 0