Sign in to follow this  
papa

sscanf - pattern matching

Recommended Posts

Hi I am trying to extract from a line of text eg: "a( -0.500001, 2.23233 ) b( 2.32222, -3.44444 )" all these 4 numbers and store them into float variables. see my code below.

void main()
{

struct Vector2D{ float x; float y;};

Vector2D a, b;

// I am reading only the first part "a( %f"  of the long text line and it does read it correctly. 
if (sscanf("a( -0.500001, 2.23233 )	b( 2.32222, -3.44444 )", "a( %f", &a.x) == 1)
{
	cout << a.x << endl; // its ok :)
}

// however when I read more stuff (after comma another number) then it fails reading. 
//It wont read data correctly and enter the if statement.. why????
if (sscanf("a( -0.500001, 2.23233 )	b( 2.32222, -3.44444 )", "a( %f, %f ) b( %f, %f )", &a.x, &a.y, &b.x, &b.y) == 1)
{
	cout << a.x << " " << a.y << "\t\t" << b.x << " " << b.y << endl;   // it never enters this if statement.
	}
}




I have to read somehow all four digits into float variables. What is wrong with the second statement? Another Question: Are there any other alterantives equally clever and short as sscanf in C++ so I could easily extract those digits from a line of text? Please let me know! thanks!!

Share this post


Link to post
Share on other sites
oouuppss. I didnt notice this. thank you very much! it works now.

I would like to ask one more question if I could. Why this wouldnt work?


// this fails as I am trying to match the second part "B( %f, %f )"
if (sscanf("a( -0.500001, 2.23233 ) b( 2.32222, -3.44444 )", "b( %f, %f )", &b.x, &b.y) == 2)
{
cout << b.x << " " << b.y << endl;
}

I understand the string doesnt start with "b(" but its starts with "a(" but I thought it would search the entire string to find "b(" then read in floats. Its really hard to find some documentation on sscanf showing how it works. All I found is that "%*s" could be used to ignore parts of strings but I am not sure how. Well I am not sure whether this would do solve my problem but basically I am trying to read only second part of the string and ignore the first part.

[Edited by - papa on September 4, 2004 11:40:47 AM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this