0

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?!

3
  • 2
    Why are you using a string to read binary data? Commented Jun 17, 2012 at 19:27
  • I suggest you switch to std::vector<char>. Commented Jun 17, 2012 at 19:28
  • How is it c question? o.O Commented Jun 17, 2012 at 19:28

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Or, simply keep it in a std::string, and use c_str() combined with length() to access the content!
Okey, there are a few zero-valued bytes in the example: hexdump -C ./binary.bin 00000000 03 01 6a 00 00 07 56 52 03 30 00 01 01. So is it possible to convert it to const char* at all?
The issue with std::vector<char> is that eventually I want to convert the data into readable content. The custom library I use only take const char* as argument. Thus I would end up with needing to convert from vector<char> into const char* instead...
"I want convert the data into readable content". There is no possible conversion between binary data and strings. All you can do with binary is print them in the hex form, or something like that.
@user1432032: Yes; your code already does obtain a valid const char *. The problem is that you cannot treat it like a string, because it isn't one.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.