[英]c++ programming with linux
我收到的浮点值为-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 ...一个值并将其放在变量中...可以有人帮我...我用过memcpy但没有用..如果我要复制8字节的值-157.571,其中包括'-'和'等8个值。 ' ....对此有任何解决方案..
如果我理解正确,则您有一个存储在某种类型的字符串中的值,并且想要从中检索浮点值。 如果是这种情况,则取决于您使用的语言。 如果使用的是C ++,则应使用std::istringstream
执行转换。 如果您使用的是C(和/或C ++的cstdio
系统而不是iostream
),则应使用sscanf
。 如果您使用的是C#,则应该使用Double.TryParse
。
假设您的float缓冲区是以下字符串 :
"-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"
您最干净的C ++方法是将其加载到std::istringstream
,然后使用该流提取浮点值。即
std::istringstream str(buffer);
现在您可以使用流中的in运算符提取浮点值,然后重复此操作,直到没有更多为止(提示:检查流标志)
str >> {float}; // then do something with {float}
(可选)您可以将此提取的值推入std::vector
以便为字符串提供浮点数。 我没有写完整的代码,只是伪代码给你一个主意...
您有一个字符串,其中包含多个浮点值,并用空格分隔。
如果可以使用strtof()
将它们转换为float
值。
float strtof( const char *nptr, char **endptr);
where
will contain the pointer to the last character that was converted, so can be used to walk through your string.nptr
is the string that you wish to convert and endptr
is a pointer to a char pointer. endptr
例如。
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++; }
应该应用适当的错误检查,以确保您不会用尽字符串的末尾等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.