# "0,1,2" to vector3(0,1,2)

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

## Recommended Posts

How can I turn a string representation of a vector into three doubles to pass to that vector? Context is getting a vector from an XML attribute, as opposed to three seperate attributes:
<point id="anchor" x="0" y="2" z="0" />
point3 pos(
atof(xPoint->Attribute("x")),
atof(xPoint->Attribute("y")),
atof(xPoint->Attribute("z"))
);
to
<point id="anchor" position="0,1,2" />
and the necessary processing to vector3

##### Share on other sites
Slightly confused - you've got the 2nd of the two options right? position="0,1,2"? Allow me to post the overkill version using boost::spirit

#include <boost/spirit.hpp>using namespace boost;using namespace boost::spirit;struct vector3d{    double x,y,z;};bool parse_vector3d( char const * str , vector3d & vector ){    return parse(str,    //  Begin grammar    (        real_p[assign_a(vector.x)]    >> ',' >> real_p[assign_a(vector.y)]    >> ',' >> real_p[assign_a(vector.z)]    )    ,    //  End grammar    space_p).full;}if ( ! parse_vector3d( "0,1,2" , my_vector3d ) ) throw bad_ju_ju;

Overkill, but I love boost :-). It'll even accept spaces in that input.

##### Share on other sites
#include <sstream>#include <string>point3 createFromString(const string& pos) {  stringstream ss(pos);  double x,y,z;  char comma; // we won't do any real validation...  ss >> x >> comma >> y >> comma >> z;  return point3(x,y,z);}point3 pos = createFromString(xPoint->Attribute("position"));

Alternatively, you could make the function be a point3 constructor, or static (factory) method.

##### Share on other sites
@MaulingMonkey: What's the performance of that like? Obviously it is at load-time so it's constant and doesn't really matter, but it could be useful in other situations too.

##### Share on other sites
I don't know boost specifically, but my parser is O(n) for n characters - it's an expensive compile time operation to build all the necessary tables though.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 13
• 9
• 15
• 14
• 46
• ### Forum Statistics

• Total Topics
634057
• Total Posts
3015283
×