使用 strstream C++ 将数字转换为字符串并返回
Converting numbers to string and back using strstream C++
我有一个程序需要我通过网络发送号码。我试图将它们转换成一个字符串,然后再使用 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);
来自您的代码:
otherStream.read(&numberBuffer[0], sizeof(int));
ReadData1 = atoi(numberBuffer);
在您的平台上,sizeof(int)
将是 4 或 8 个字节。当然,像这样的数字:
1234567890
十个字符长,十个字节,显然,这不会读取所有内容。您最终会得到 1234 或 12345678,具体取决于您的平台。
将两个格式化值写入流后,没有任何分隔,流包含
980.5
您出于某种原因读回 sizeof(int)
个字节;如果 int
中有四个字节,那么你会得到 980.
,atof
转换为 980
,忽略 .
。然后你读取 sizeof(float)
字节,给出剩余的 5
,然后是垃圾,因为你已经到达流的末尾。
一种方法是用 space 来分隔值:
stream << data1 << ' ' << data2;
并使用格式化输入读回它们:
otherStream >> ReadData1 >> ReadData2;
您挑选出的值就好像它们是二进制编码到流中的一样,但事实并非如此。它们是人类可读的 ASCII 表示形式。当您应用 atoi
和 atof
时,您似乎理解了这一点,但是您已经选择了这些值,就好像它们 是 的二进制格式一样,您使用sizeof
.
您的线路协议将需要某种方式来分隔值,您将需要解析它们。或者您的线路协议可以首先对数据进行二进制编码,但随后您需要设置有关数据类型宽度、编码和字节顺序的约定。
我有一个程序需要我通过网络发送号码。我试图将它们转换成一个字符串,然后再使用 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);
来自您的代码:
otherStream.read(&numberBuffer[0], sizeof(int));
ReadData1 = atoi(numberBuffer);
在您的平台上,sizeof(int)
将是 4 或 8 个字节。当然,像这样的数字:
1234567890
十个字符长,十个字节,显然,这不会读取所有内容。您最终会得到 1234 或 12345678,具体取决于您的平台。
将两个格式化值写入流后,没有任何分隔,流包含
980.5
您出于某种原因读回 sizeof(int)
个字节;如果 int
中有四个字节,那么你会得到 980.
,atof
转换为 980
,忽略 .
。然后你读取 sizeof(float)
字节,给出剩余的 5
,然后是垃圾,因为你已经到达流的末尾。
一种方法是用 space 来分隔值:
stream << data1 << ' ' << data2;
并使用格式化输入读回它们:
otherStream >> ReadData1 >> ReadData2;
您挑选出的值就好像它们是二进制编码到流中的一样,但事实并非如此。它们是人类可读的 ASCII 表示形式。当您应用 atoi
和 atof
时,您似乎理解了这一点,但是您已经选择了这些值,就好像它们 是 的二进制格式一样,您使用sizeof
.
您的线路协议将需要某种方式来分隔值,您将需要解析它们。或者您的线路协议可以首先对数据进行二进制编码,但随后您需要设置有关数据类型宽度、编码和字节顺序的约定。