Reputation: 13257
I have data in the following format in a file
( p1, p2 ) (p3, p4 ) ( p5, p6 )
How do i read this in C++, I can read a line and parse it , but I was looking for some C++ stl
way to read this kind of format.
Upvotes: 0
Views: 342
Reputation: 76788
It depends on the format you want to represent the data in your program. One way is to have a struct
with a custom stream-extraction operator:
struct Data {
int val1; // just assuming int for the data-type
int val2;
};
std::istream & operator>>(std::istream& input, Data & obj) {
input.ignore(2, '('); // skip all including opening brace
input >> obj.val1;
input.ignore(2, ','); // skip comma
input >> obj.val2;
input.ignore(2, ')'); // skip closing brace
return input;
}
As @Seth Carnegie demonstrates in an answer to a similar question, you can also use INT_MAX
to make sure you skip enough - however, using std::numeric_limits<std::streamsize>::max()
would be even better.
Then you can read all the contents of the file like this:
std::vector<Data> all_data;
std::ifstream input_file("your_file.txt");
std::copy(std::istream_iterator<Data>(input_file),
std::istream_iterator<Data>(),
std::back_inserter(all_data));
Here is a complete working example.
Upvotes: 2