简体   繁体   中英

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:

  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

No way ... do I have to use sprintf !??! Unfortunately I cannot use boost or C++11 ...

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. 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). As for real values such as 16.2 you need four unsigned chars to store it for every symbol it has - '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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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