这是我的问题:
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
Unsigned char 值是一个字节值。 一个字节足以存储 INTEGER 而不是 0-255 范围内的实数,或者仅存储一个符号如“1”、“2”等。 因此,您可以将数字 12 存储在 unsigned char 值中,但不能存储“12”字符串,因为它由 2 个 char 元素组成 - '1' 和 '2'(普通 c 字符串甚至有第三个 ' ' 字符串终止字符)。 至于像 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;
}
带STL设计的直线:
typedef std::basic_istringstream<unsigned char> uistringstream;
与
合作typedef std::basic_string<unsigned char> ustring;
和转换
ustring ustr = (const unsigned char*) "char data";