2014-10-16 279 views
0

我无法将常量字符转换为字节。我正在阅读使用ifstream的文件,它给我的内容作为字符串,然后我使用c_str()将字符串转换为常量字符。然后尝试将其插入到字节数组以用于数据包发送目的。我是新来的C + +不能理解我必须如何将字符转换为字节,需要你的帮助球员。这里是我的一段代码,请给我一些建议从`const char *'转换为`byte'

byte buf[42]; 

const char* fname = path.c_str(); 

ifstream inFile; 
inFile.open(fname);//open the input file 

stringstream strStream; 
strStream << inFile.rdbuf();//read the file 
string str = strStream.str();//str holds the content of the file 

vector<string> result = explode(str,','); 

for (size_t i = 0; i < result.size(); i++) { 
    buf[i] = result[i].c_str(); // Here is Error 
    cout << "\"" << result[i] << "\"" << endl; 
} 

system("pause"); 

这是我从文件中取数据:(0x68,0x32,0x01,0x7B,0x01,0x1F,0x00,0x00,0x00,0x02,0x00, 0x00,0x00,0x00)

+3

这个'byte'类型是如何定义的?它不是标准C++的一部分... – 2014-10-16 13:36:53

+0

您正试图在字节数组中存储指向字符串的指针。 1个字节不能包含整个字符串。我不确定你想要做什么。 – 2014-10-16 13:38:54

+1

'byte'不是C++ 11的标准类型。你的意思是[int8_t](http://en.cppreference.com/w/cpp/types/整数)? – 2014-10-16 13:41:07

回答

0

我自己做到了里面,现在我会解释的解决方案。所以我想每个“,”字符串(0x68,0x32,0x03,0x22 etc ..)变量拆分,然后将其转换为十六进制值后全部输入到字节数组为16位十六进制值。

char buf[42]; // Define Packet 

const char* fname = path.c_str(); // File Location 


ifstream inFile; // 
inFile.open(fname);//open the input file 

stringstream strStream; 
strStream << inFile.rdbuf();//read the file 
string str = strStream.str();//str holds the content of the file 



vector<string> result = explode(str,','); // Explode Per comma 


for (size_t i = 0; i < result.size(); i++) { // loop for every exploded value 

unsigned int x; 
std::stringstream ss; 
ss << std::hex << result[i]; // Convert String Into Integer value 
ss >> x; 
buf[i] = x; 

printf(&buf[i],"%04x",x); //Convert integer value back to 16 bit hex value and store into array 


    } 



    system("pause"); 

感谢所有的重播。

0

您正试图将字符串(多个字符)分配给单个字节。它不适合。 试着这么做

循环开始前补充一点:然后

size_t bufpos = 0; 

循环

const string & str = resulti[i]; 
for (size_t strpos = 0; strpos < str.size() && bufpos < sizeof(buf); ++strpos) 
{ 
    buf[bufpos++] = str[strpos]; 
} 
+0

是的但爆炸字符串(0x68,0x32,0x01,0x7B,0x01,0x1F,0x00 ...)作为1十六进制值,并需要像这样把数组[0] = 0x68,并且我想要有与此字节类似的字节数组buf [0121] = { 0x68,0x32,0x01,0x7B,0x01,0x1F,0x00,0x00,0x00, 0x02,0x00,0x00,0x00,0x00,0x00,0x03, 0x12,0x00,0x57,0x12,0x00 ,0x65,0x12,0x00,0x6C,0x12,0x00,0x63,0x12,0x00,0x6F,0x12,0x00,0x6D,0x12,0x00,0x65,0x00,0x00,0x00, 0x86,0x03 } – DTDest 2014-10-16 13:46:50

+0

其种类当你不断改变目标并添加新元素时,很难回答你的问题。 'array [0]'从哪里来?我建议你退后一步,确定你正在努力达到的目标,而不是将你所采取的方法放在低水平的问题上。 – 2014-10-16 13:50:45

+0

我的意思是字节buf [0]作为数组[0],但无论如何,请回答我,如果你知道,如果我有字符串尝试=“0x23”是否有可能将此字符串转换为字节值并将其插入字节buf [1] = {0x23},(对不起,我的英语) – DTDest 2014-10-16 13:55:27