dimanche 26 avril 2015

Converting numbers to string and back using strstream C++

I have a program that requires me to send numbers over a network. I'm attempting to convert them into a string and then back again using strstream. The issue I'm having is that when it comes to taking the values off of the stream I seem to be reading the incorrect number of bytes. I suspect its probably due to the initial string conversion but I'm not exactly sure. Does anybody know what's wrong?

My code is as follows

int data1 = 98;
float data2 =  0.5f;

std::strstream stream;
stream << data1 << data2;

string networkData = stream.str();  //assume this line is the string transferred over the network


char numberBuffer[4];
int ReadData1;
float ReadData2;

std::strstream otherStream;
otherStream << networkData;

otherStream.read(&numberBuffer[0], sizeof(int));   //reads 980.f
ReadData1 = atoi(numberBuffer);    //prodces 980

otherStream.read(&numberBuffer[0], sizeof(float));  //reads 5 followed by junk
ReadData2 = atof(numberBuffer);

Aucun commentaire:

Enregistrer un commentaire