still can't get it..

I posted this last time but I am hoping I can get some more input. This seems like a pretty easy task to implement but I can't figure out the best way of doing it. I have some data that looks like the following:

+ alpha 3.631657 0.911405 0.400035 0.096500
+ gamma 0.057156 0.133028 -0.452153 0.881964
+ He3 3.338188 0.229391 0.971863 0.053501
+ B10[0.0] 7.585255 -0.481513 -0.543344 0.687693

The first entries of each line tell you what kind of particle you are dealing with and the next four entries are energy, x-position, y-position and z-position respectively. I process this data with the getline function:

1
2
3
4
5
ifstream myfile("C:\\file.txt");
while (myfile.good())
{
getline(myfile, line);
}


Next I need to extract the energy and x, y and z positions from each line so that that you would be able to write the parameters from each line like:

1
2
3
4
energy = ....
x_pos = ....
y_pos = ....
z_pos = ...


Is there some function I can use to pull values separated by a space easily? Maybe something similar to the line.find() or line.at() functions?
one way you could try and do it, is look for a " " <-- space..

from there you can break apart the information
I think I can do this using the sscanf function.
yeah, also you need to look for a \0 (the end of the line)

you can excuse all chars and just look for numbers using isdigit
I am scanning each line in a loop. Inside of my loop, after a line is taken I will do something like:

1
2
3
float x, y, z, energy;
char plus, particle;
sscanf(line.c_str(),"%s %s %f %f %f %f", &plus, &particle, &energy, &x, &y, &z);


It seems this should then yield the following for the first line:

energy = 3.631657
x = 0.911405
y = 0.400035
z = 0.096500

When I try this I get some nonsensical value for energy, x, y and z. Something like 1.03xe8. Any ideas??????????
it seems like a conversion problem, try changing the output with a designated float

%1.5f 1 constant, 5 decimal places.. see if that helps.. it looks like its trying to convert it to significant notation
Yes got it!!! thanks!
NP glad i could help :)
You are very likely clobbering memory you shouldn't be. The %s in the format string tells sscan f to interpret the memory pointed to by &plus and &particle as c strings; as you've defined them, they are single characters. particle looks like it actually should be a string.

You might want to try a more c++esque approach:

#include <sstream>

float x, y, z, energy ;
char plus ;
string particle ;

istringstream in(line) ;

in >> plus >> particle >> energy >> x >> y >> z ;







Topic archived. No new replies allowed.