我有一个程序要求我通过网络发送号码。我试图将它们转换为字符串然后再使用strstream返回。我遇到的问题是,当从流中取出值时,我似乎正在读取不正确的字节数。我怀疑它可能是由于最初的字符串转换,但我不完全确定。有人知道什么是错的吗?
我的代码如下
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);
答案 0 :(得分:3)
将两个格式化的值写入流后,没有任何内容可以将它们分开,流包含
980.5
您出于某种原因读回了sizeof(int)
个字节;如果int
中有四个字节,则会980.
atof
转换为980
忽略.
。然后你读取sizeof(float)
字节,给出剩余的5
,然后垃圾,因为你已到达流的末尾。
一种方法是用空格来编写它们来分隔值:
stream << data1 << ' ' << data2;
并使用格式化输入读回来:
otherStream >> ReadData1 >> ReadData2;
答案 1 :(得分:0)
从你的代码:
otherStream.read(&numberBuffer[0], sizeof(int));
ReadData1 = atoi(numberBuffer);
在您的平台上,sizeof(int)
将为4或8个字节。当然,有一些像:
1234567890
十个字符长,十个字节,这显然不会读完所有内容。您最终会得到1234或12345678,具体取决于您的平台。
答案 2 :(得分:-1)
您选择的值就好像它们是二进制编码到流中一样,但它们不是。它们是人类可读的ASCII表示。当您应用atoi
和atof
时,您似乎明白了这一点,但您已经选择了这些值,就好像他们 的二进制格式一样,使用{{1 }}
您的行协议需要某种方式来分隔值,您需要解析它们。或者您的行协议可以首先对数据进行二进制编码,但是您需要根据数据类型宽度,编码和字节顺序设置约定。