2013-06-28 63 views
0

這是我的問題:從字符串流爲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!??!不幸的是我不能使用升壓或C++ 11 ...

TIA

+0

'is >> is(unsigned int&)myChar [0];'? – 2013-06-28 09:31:35

+0

好的。大! 但在這種情況下,我應該投下「任何類型」。例如:最新的一個是浮動。到目前爲止似乎是最好的解決方案;-) – Kasper

+0

甚至更​​好,'unsigned int buf [4];是>> buf [0] ... >> buf [3]; unsigned char ch [] = {buf [0],buf [1],buf [2],buf [3]};' – 2013-06-28 09:37:54

回答

0

無符號的字符值是一個字節值完全相同。 一個字節就足以存儲0到255範圍內的INTEGER而不是實數,或者只有一個符號存儲爲'1','2'等等。 因此,你可以將數字12存儲在無符號字符值中,但不能存儲「12」字符串,因爲它包含2個字符元素 - '1'和'2'(普通c字符串甚至有第三個'\ 0'字符串終止字符)。 對於像16.2這樣的實際值,你需要四個無符號字符來存儲它所有的符號 - '1','6','。','2'。

+0

我知道我不能將字符串'12'存儲到一個字節:-) 的確,我的問題確切地說是:使用字符串('12')的整數表示形式(12) stringstream可能......就這樣。和H2CO3提出了建議。 謝謝。 – Kasper

0

我知道的唯一解決方案是解析字符串。這裏是一個例子:

#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; 
} 
相關問題