开发者

c++ programming with linux

i am receiving a b开发者_如何学JAVAuffer with float values like -157.571 91.223 -165.118 -59.975 0.953 0 0.474 0 0 0.953 0 0.474 0.474 0 5.361 0 0 0.474 0 5.361...but they are in characters...now i want to retrieve one by one value and put it in a variable...can any one help me please...i have used memcpy but no use..if i am copying 8 bytes its taking as -157.571 with 8 values including '-' and '.' .... is there any solution for this ..


If I'm understanding correctly, you have a value stored in a string of some kind and you want to retrieve a floating point value out of it. If that is the case, it depends on the language you're using. If you're using C++, you should use a std::istringstream to perform the conversion. If you're using C, (and/or the cstdio system from C++ instead of iostream), you should use sscanf. If you're using C#, you should be using Double.TryParse.


Let's say your buffer of floats is this string:

"-157.571 91.223 -165.118 -59.975 0.953 0 0.474 0 0 0.953 0 0.474 0.474 0 5.361 0 0 0.474 0 5.361"

your cleanest C++ approach is to load this into a std::istringstream and then use the stream to extract the float values.. i.e.

std::istringstream str(buffer);

now you can use the stream in operator to extract a float value, and repeat this until there are no more (hint: check the stream flags)

  str >> {float}; // then do something with {float}

Optionally you can push this extracted value in to a std::vector to give you the floats in the string. I've not written out the full code, just the pseudo to give you an idea...


You've got a string that contains a number of floating point values separated by a space.

If You could use strtof() to convert them to float values one at a time.

float strtof( const char *nptr, char **endptr);

where nptr is the string that you wish to convert and endptr is a pointer to a char pointer. endptr will contain the pointer to the last character that was converted, so can be used to walk through your string.

eg.

char *rawString;
char **walkPtr;
float convertedValue;

/* do something to collect the next series of floats */

/* and now do the conversions */
*walkPtr = rawString;
while( still_some_string_to_process )
{
    convertedValue = strtof( *walkPtr, walkPtr );

    // increment the pointer to skip over the delimiting space
    *walkPtr++;
}

Appropriate error checking should be applied to ensure you don't run off the end of the string, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜