我想要做的是将字符串转换为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; }这将返回“string length:13”和“const char length:3”。
显然,使用myString.c_str()将字符串转换为const char*时会有一些数据丢失!
如何在不丢失二进制数据的情况下将字符串转换为const char *?
What I want to do is to convert a string into const char*.
Ideally I could just use "const char* myConstChar = myString.c_str()" but as my example below shows; it doesn´t work well for binary data:
#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; }This returns "string length: 13" and "const char length: 3".
Apparently there are some loss of data when converting string to const char* using myString.c_str()!
How do I convert a string to const char* without losing binary data?!
最满意答案
这几乎可以肯定,因为您的二进制数据包含零值字节。 这些与null-terminators相同,其功能类似于strlen用于确定字符串的结尾。
可以说任意二进制数据不应被视为字符串。 所以请改用std::vector<char> ,不要使用像strlen这样的函数。
This is almost certainly because your binary data contains zero-valued bytes. These are identical to null-terminators, which functions like strlen use to determine the end of a string.
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.
更多推荐
发布评论