-1

This is probably a rookie question, but I couldn't find the answer in the search. I got a variable: char buffer[ 128 ]; now I've made it's value through a search script, coming from a big file to:

"Density @ 15°C kg/m3 990.1 ( 991.0 Max ).BR.Viscocity @50°C cSt 355."

This is a specific line of 128 chars that I'm intrested in, more specifically the float "990.1". I need to get this out of all my files which is a bunch so getting the program to search for that specific text is not ok (I'll need to loop through a lot of files), it has to search for the first float. I've been trying with sscanf, but been stuck on it for a while now so I thought I'd ask.

Any help would be much appreciated!

James D
  • 1,975
  • 2
  • 17
  • 26

2 Answers2

0

If the float value you're looking for is always between kg/m3 and (space) you can use strstr to exctract the piece of string and then convert to float.

http://www.cplusplus.com/reference/cstring/strstr/

char *start;
char *end;
double val;

start = strstr( buffer, "kg/m3 " );
start += 6;
end = strstr( start, " " );
*end = 0;

val = atof( start );
*end = ' ';

Note that I look for the termination space and convert to null termination character.

So atof parses buffer starting from start and stops after the last digit.

Later I restore the space to leave the original string unchanged.

Paolo
  • 15,233
  • 27
  • 70
  • 91
0

Thanks for the input everybody. So I went with the comments answer of πάντα ῥεῖ by using parsing, mainly because of the whitespace giving me issues on Paolo's suggestion. This is what has worked out for me:

            float num;
            string dummy;
            istringstream iss( buffer );
            while( !iss.eof() && dummy != "(") 
            {
                iss >> num;
                if(iss.fail()) {

                    iss.clear();
                    iss >> dummy;
                    continue;
                }                   
            }
James D
  • 1,975
  • 2
  • 17
  • 26