[英]How to parse numeric strings recieved over TCP
I'm receiving data from my sensor via TCP and the output looks like this: <-0.040000 , -0.005000 , 0,025000 , 0,990000 , -0,000500 , 0.033000 > 我正在通过TCP从传感器接收数据,并且输出看起来像这样:<-0.040000,-0.005000,0,025000,0,990000,-0,000500,0.033000>
It's a 6 times double value. 这是6倍的两倍。 I need only first three.
我只需要前三个。 Forces in X,Y and Z direction to get their resultant force.
沿X,Y和Z方向的力获得其合力。 I was told I'm reciving 'sensor streams string representation of double' and that I should use atof function which takes a string representing of a floating point number and returns a double.
有人告诉我,我正在接收“传感器流字符串表示形式为double的表示形式”,我应该使用atof函数,该函数采用表示浮点数的字符串并返回一个double形式。
So, the problem is. 所以,问题是。 I'm using following code to receive data from sensor
我正在使用以下代码从传感器接收数据
char recvbuf[DEFAULT_BUFFER_LENGTH];
int iResult = recv(ConnectSocket, recvbuf, DEFAULT_BUFFER_LENGTH, 0);
double n;
n = atof (recvbuf);
Output is always wrong, either I get wrong data, 30000 instead of 0.1414, or I read 0.15 as 0. Any tips on how should I get all 3 data? 输出总是错误的,要么我得到了错误的数据,即30000而不是0.1414,要么我将0.15读为0。关于如何获取所有3个数据的任何提示? I use BUFFER=50, cuz I don't need to read more and I don't even know how long in total, string from sensor is.
我使用BUFFER = 50,因为我不需要阅读更多,甚至不知道传感器发出的字符串总共有多长时间。
You need to break this down into smaller steps. 您需要将其分解为较小的步骤。 For example:
例如:
recvbuf
) for a start-of-data marker '<'
. recvbuf
)中搜索数据开始标记'<'
。 '>'
, go to step 4. '>'
,请转到步骤4。 atof
or fscanf
. atof
或fscanf
将每个值字符串转换为数字。 You are calling atof
at arbitrary points in the data stream. 您正在数据流中的任意点调用
atof
。 That will not work. 那不管用。
There are several steps needed to do this reliably. 要可靠地执行此操作,需要执行几个步骤。
The data you get from recv
can a partial data set that needs to be appended to the preceding and by the following recv
calls's data. 从
recv
获取的数据可以是部分数据集,需要将其追加到前面和后面的recv
调用的数据之后。 This is sometimes done in a pipeline fashion that reads characters from the recvbuf
into a parsebuf
. 有时这是通过管道方式完成的,该方式将从
recvbuf
中读取字符到parsebuf
。
Your data looks to be framed with (
and )
so your copy routine can skip to the first (
and then copy data up to the following )
您的数据看起来像用
(
和)
框起来,因此您的复制例程可以跳到第一个(
然后将数据复制到以下内容)
When the copy routine hits the end of the recvbuf
it should call recv
again to fill the recvbuf
and continue framing the data from the start of recvbuf
where it left off in parsebuf
当复制例程到达
recvbuf
的末尾时,它应再次调用recv
来填充recvbuf
并继续在recvbuf
的开头将数据recvbuf
中以对其进行parsebuf
At each )
the data in the parsebuf
will always be <x> , <y> , <z> , ...
so your atof
call has something reasonable to deal with. 在每个
)
中, parsebuf
的数据将始终为<x> , <y> , <z> , ...
因此您的atof
调用可以合理处理。 Consider using fscanf
考虑使用
fscanf
Reset the pointer to the parsebuf
after each conversion. 每次转换后,将指针重置为
parsebuf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.