# STL or Boost equivalent of sscanf?

This topic is 4249 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, Im trying to pass a half-life .map file. Planes are defined in the file like this:
( 432 0 96 ) ( 432 128 96 ) ( 560 0 96 ) FIFTIES_WALL14Y [ 1.00000 0.00000 0.00000 -432.00000 ]  [ 0.00000 -1.00000 0.00000 0.00000 ]  0  1.00000 1.00000


Now, normally I'd use sscanf to parse this string, but I'm thinking there must be a C++ way of doing this with streams. But I cant find any information on how to do this without reverting back to sscanf. Boost has a format library, but that only works the other way (ie putting arguments into a string not taking them out). Anyone know the best way of doing this? Thanks, Luke.

##### Share on other sites
boost::regex (or tr1::regex if your compiler supports it) or boost::spirit

##### Share on other sites
You could use std::istringstream

##### Share on other sites
If you're able to properly parse it with sscanf then ordinary streams are probably adequate. For more advanced needs you might try Boost.Tokenizer or maybe even Boost.Spirit, though that may be overkill.

##### Share on other sites
Something like this:

struct triple {  int values[3];};struct quad {  float values[4];}template<typename T>void expect(istream& is, const T& expected) {  T got;  is >> got;  if (got != expected) { is.setstate(ios::fail_bit); }}// For safety... when checking a char*, use the string version,// so that 'got' will actually be a valid buffer for reading.void expect(istream& is, const char*& expected) {  expect(is, string(expected));}void rewind_if_failed(istream& is, streampos pos) {  if (!is) {    iostate tmp = is.rdstate();    is.clear();    is.seekg(pos);    is.setstate(tmp);  }}// These are implemented like the primitive types, in that if the thing can't// be read, then nothing should appear consumed from the stream, and the// stream will be in a failed state. That allows you to handle a situation// where two possible kinds of things are valid at a given point in the// stream: if one read-attempt fails, reset and try to read the other type.istream& operator>>(istream& is, triple& t) {  streampos current = is.tellg();  expect(is, "(");  is >> t.values[0] >> t.values[1] >> t.values[2];  expect(is, ")");  rewind_if_failed(is);}istream& operator>>(istream& is, quad& q) {  streampos current = is.tellg();  expect(is, "[");  is >> q.values[0] >> q.values[1] >> q.values[2] >> q.values[3];  expect(is, "]");  rewind_if_failed(is);}// now we use a stringstream like this:string line;getline(is, line); // load a line of the file into our string.stringstream ss(line);triple a, b, c;string texture_name;quad x, y;float f1, f2, f3;line >> a >> b >> c >> texture_name >> x >> y >> f1 >> f2 >> f3;

1. 1
2. 2
Rutin
22
3. 3
4. 4
frob
18
5. 5

• 33
• 13
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
632566
• Total Posts
3007107

×