How to parse numeric strings recieved over TCP

给你一囗甜甜゛ 提交于 2019-12-12 02:44:09

问题


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 >

It's a 6 times double value. I need only first three. Forces in X,Y and Z direction to get their resultant force. 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.

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? 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.


回答1:


You need to break this down into smaller steps. For example:

  1. Receive an arbitrary sized packet from socket.
  2. Search in the packet buffer (recvbuf) for a start-of-data marker '<'.
  3. Copy all the following characters from the packet buffer to a parse buffer (which you need to create. Make it big enough to hold the longest possible data representation of the 6 data points).
    • 3A. If you find an end-of-data marker '>', go to step 4.
    • 3B. If you run out of data, receive the next packet and repeat step 3.
  4. Break parse buffer at commas into N value strings.
  5. Convert each value string into a number with atof or fscanf.
  6. Go to Step2, starting from the character after the last end-of-data.



回答2:


You are calling atof at arbitrary points in the data stream. That will not work.

There are several steps needed to do this reliably.

  1. 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. This is sometimes done in a pipeline fashion that reads characters from the recvbuf into a parsebuf.

  2. 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 )

  3. 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

  4. At each ) the data in the parsebuf will always be <x> , <y> , <z> , ... so your atof call has something reasonable to deal with. Consider using fscanf

  5. Reset the pointer to the parsebuf after each conversion.



来源:https://stackoverflow.com/questions/33618837/how-to-parse-numeric-strings-recieved-over-tcp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!