I am receiving a buffer over a udp socket connection. The code is c++. The output is like:
>>375.5,25.3
where the numbers are separated by a comma and no spaces. And every 100ms a new set of numbers a sent. so like:
>>375.5,25.3
>>435.6,0.0
>>2500.34,55.2
and so on.
I am trying to put the first number in var1 and the second number in var2 for each new set. var1 and var2 are not arrays. Imagine I just need to print something like:
>>var1=375.5
var2=25.3
>>var1=435.6
var2=0.0
Here is the code that I am using:
recv_len = recvfrom(s, buff, sizeof(buff), 0, (struct sockaddr *)&si_other, (socklen_t*)&slen);
if (recv_len== -1)
{
printf("Receiving message failed");
exit(0);
}
buff[recv_len] = '\0';
std::vector<int> vect;
std::stringstream ss(buff);
int i;
while (ss >> i)
{
vect.push_back(i);
if (ss.peek() == ',' || ss.peek() == ' ')
ss.ignore();
}
var1 = vect.at(0);
var2 = vect.at(1);
printf("Received packet from %s:%d\nData:%s\n\n",inet_ntoa(si_other.sin_addr),ntohs(si_other.sin_port),buff);
cout<<var1<<endl;
cout<<var2<<endl;
the output I get is an error, something about the size being 1. (sorry, I didn't save the output of this to give the exact error output. I will edit tomorrow.) when I comment out the "var2 = vect.at(1)" the output is:
>>Received packet from 127.0.0.1:31029
Data: 375.5,25.3
375.5
0
so it shows that there is both numbers that I need, but it won't allow me to separate them. I got the separate by comma from this: Parsing a comma-delimited std::string but is giving me an error.
I just need to separate the buffer each time it comes in like:
>>375.5,25.3
comes in, put var1 = 375.5 and var2 = 25.3, then
>>435.6,0.0
comes in, put var1 = 435.6 and var2 = 0.0
>>2500.34,55.2
comes in, put var1 = 2500.34 and var2 = 55.2
and so on.
---------------------EDIT----------------------------
The error I would receive that I couldn't remember from above was:
>>Terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 1) >= this->size() (which is 1)