C++ 从stringstream到无符号字符
这是我的问题:C++ 从stringstream到无符号字符,c++,stringstream,C++,Stringstream,这是我的问题: std::string str = "12 13 14 15 16.2"; // my input 我想要 unsigned char myChar [4]; // where myChar[0]=12 .. myChar[0]=13 ... etc... 我尝试使用istringstream: std::istringstream is (str); unsigned char myChar[4]; is >> myChar[0] // here
std::string str = "12 13 14 15 16.2"; // my input
我想要
unsigned char myChar [4]; // where myChar[0]=12 .. myChar[0]=13 ... etc...
我尝试使用istringstream:
std::istringstream is (str);
unsigned char myChar[4];
is >> myChar[0] // here something like itoa is needed
>> myChar[1] // does stringstream offers some mechanism
//(e.g.: from char 12 to int 12) ?
>> myChar[2]
>> myChar[3]
但我得到了(显然)
myChar[0]=1。。myChar[1]=2。。myChar[2]=3
不可能。。。我必须使用sprintf吗!??!不幸的是,我不能使用boost或C++11
TIA无符号字符值正好是一个字节的值。 一个字节足以存储0-255范围内的整数而不是实数,或者仅存储一个符号“1”、“2”等。 因此,可以将数字12存储在无符号字符值中,但不能存储“12”字符串,因为它由两个字符元素组成—“1”和“2”(普通c字符串甚至还有第三个“\0”字符串终止字符)。
对于16.2之类的实值,需要四个无符号字符来存储它的每个符号—“1”、“6”、“2”。我知道的唯一解决方案是解析字符串。以下是一个例子:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
stringstream ss("65 66 67 68 69.2");
string value;
int counter=0;
while (getline(ss, value, ' '))
{
if (!value.empty())
{
cout << (unsigned char*) value.c_str() << endl;
counter++;
}
}
cout << "There are " << counter << " records." << endl;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
stringstream ss(“65 66 67 68 69.2”);
字符串值;
int计数器=0;
while(getline(ss,value,'))
{
如果(!value.empty())
{
好的,太好了!但是在这种情况下,我应该对“任意类型”进行强制转换。例如:最新的一个类型是浮点型。到目前为止似乎是最好的解决方案;-)甚至更好,无符号int buf[4];is>>buf[0]…>>buf[3];无符号字符ch[]={buf[0],buf[1],buf[2],buf[3]}
将16.2
转换为无符号字符
值的结果是什么?操作…刚刚实现!愚蠢的问题:-)我知道我不能将字符串“12”存储到一个字节:-)事实上,我的问题正是:使用字符串(“12”)的整数表示(12)的最优雅方法可能使用stringstream…仅此而已。H2CO3提出了一个建议。谢谢。