[英]from stringstream to unsigned char
this is my problem: 这是我的问题:
std::string str = "12 13 14 15 16.2"; // my input
I'd like 我想要
unsigned char myChar [4]; // where myChar[0]=12 .. myChar[0]=13 ... etc...
I tried to use istringstream: 我尝试使用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]
But I got (obviously) 但是我(显然)
myChar[0]=1 .. myChar[1]=2 .. myChar[2]=3
myChar [0] = 1 .. myChar [1] = 2 .. myChar [2] = 3
No way ... do I have to use sprintf !??! 没办法...我必须使用sprintf!??! Unfortunately I cannot use boost or C++11 ...
不幸的是我不能使用boost或C ++ 11 ...
TIA TIA
Unsigned char value is one byte value exactly. 无符号字符值恰好是一个字节值。 One byte is enough to store INTEGER not real number in range 0-255 or just ONE symbol as '1', '2' and so on.
一个字节足以存储INTEGER非实数,范围为0-255,或仅存储一个符号为'1','2',依此类推。 So you can store number 12 in unsigned char value but you can't store "12" string, because it consists of 2 char elements - '1' and '2'(normal c string even has third '\\0' string terminating character).
因此您可以将数字12存储在无符号char值中,但不能存储“ 12”字符串,因为它由2个char元素组成-'1'和'2'(普通c字符串甚至具有第三个'\\ 0'字符串终止字符)。 As for real values such as 16.2 you need four unsigned chars to store it for every symbol it has - '1', '6', '.', '2'.
对于诸如16.2之类的实数值,您需要四个无符号字符来存储它具有的每个符号-'1','6','。','2'。
The only solution i know is to parse the string. 我知道的唯一解决方案是解析字符串。 Here is a example:
这是一个例子:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.