将字符串转换为const char *(带二进制数据)(Convert string to const char* (with binary data))

系统教程 行业动态 更新时间:2024-06-14 16:57:17
将字符串转换为const char *(带二进制数据)(Convert string to const char* (with binary data))

我想要做的是将字符串转换为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.

更多推荐

本文发布于:2023-04-12 20:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/bc1a059143d1682478f02987f339ef9d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   二进制数   const   binary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!