繁体   English   中英

从stringstream到unsigned char

[英]from stringstream to unsigned char

这是我的问题:

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

无符号字符值恰好是一个字节值。 一个字节足以存储INTEGER非实数,范围为0-255,或仅存储一个符号为'1','2',依此类推。 因此您可以将数字12存储在无符号char值中,但不能存储“ 12”字符串,因为它由2个char元素组成-'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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM