2012-06-17 119 views
0

我想要做的是將字符串轉換爲const char *。理想情況下,我可以使用「const char * myConstChar = myString.c_str()」,但正如下面的示例所示;它不適用於二進制數據:將字符串轉換爲const char *(使用二進制數據)

#include <iostream> 
#include <fstream> 
#include <stdio.h> 
#include <string.h> 

using namespace std; 

int main(){ 
    string myString; // This need to be string 
    ifstream infile; 
const char* myConstChar; // This need to be const char* 

infile.open("binary.bin"); 

if(infile){ 
     while(getline(infile, myString)){ 
     std::cout << "Data: " << myString << " string length: "; 
      std::cout << myString.length() << "\n"; 
      myConstChar = myString.c_str(); 
      std::cout << "const char Data: " << myConstChar; 
      std::cout << " const char length: "<< strlen(myConstChar) <<"\n"; 
     } 
    } 

    infile.close(); 
    return 0; 
} 

這將返回「字符串長度:13」和「常量字符長度:3」。

當使用myString.c_str()將字符串轉換爲const char*時,顯然存在一些數據丟失!

如何將字符串轉換爲常量字符而不丟失二進制數據?

+2

爲什麼使用字符串來讀取二進制數據? – shf301

+0

我建議你切換到'std :: vector '。 – jrok

+0

它是如何[標籤:C]問題? o.O – Griwes

回答

4

這幾乎肯定是因爲您的二進制數據包含零值字節。這些與空終止符相同,其功能類似於strlen用於確定字符串的結尾。

這是有爭議的任意二進制數據不應被視爲一個字符串。因此請使用std::vector<char>,而不要使用像strlen這樣的功能。

+0

或者,只需將其保存在std :: string中,並使用c_str()與length()組合以訪問內容! –

+0

Okey,在這個例子中有幾個零值字節:hexdump -C ./binary.bin 00000000 03 01 6a 00 00 07 56 52 03 30 00 01 01.所以有可能將它轉換爲const char *在所有? – user1432032

+0

std :: vector 的問題是,最終我想將數據轉換爲可讀內容。我使用的自定義庫只使用const char *作爲參數。因此,我最終將需要從矢量轉換爲const char *而不是... – user1432032

相關問題