0

我想要做的是将字符串转换为 const char*。

理想情况下,我可以只使用“const char* myConstChar = myString.c_str()”,但如下面的示例所示;它不适用于二进制数据:

#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”和“const char 长度:3”。

const char*显然,将字符串转换为using时会丢失一些数据myString.c_str()

如何在不丢失二进制数据的情况下将字符串转换为 const char*?!

4

1 回答 1

4

这几乎可以肯定是因为您的二进制数据包含零值字节。这些与空终止符相同,它们的功能类似于strlen用于确定字符串的结尾。

It's arguable that arbitrary binary data shouldn't be treated as a string. So use std::vector<char> instead, and don't use functions like strlen.

于 2012-06-17T19:28:09.633 回答