簡體   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