0

This is the code I am seeking to do

std::string json_str;
const char json[] = json_str;

this is my try

const char json [json_str.size()] = {(char) json_str.c_str ()};

But it gives me the error "cast from 'const char*' to 'char' loses precision"

Please help. Thank you.

5
  • use json_str.c_str() it will return a const char *. Commented Aug 14, 2015 at 15:53
  • C++ doesn't have variable length arrays. An array's dimensions must come from a compile-time constant. Commented Aug 14, 2015 at 15:54
  • 1
    You can't assign directly to an array from an expression that cannot be reduced at compile time. Commented Aug 14, 2015 at 15:55
  • 1
    Is there a reason you need to const char* when you have the string? If you have a function that takes a const char* then just use json_str.c_str() as the parameter. Commented Aug 14, 2015 at 15:55
  • @NathanOliver I suppose you're right; document.Parse (json_str.c_str()) does compile; now to see if it works or not Commented Aug 14, 2015 at 15:59

2 Answers 2

2
#include <string>

int main() {
    std::string json_str;
    const char *json = json_str.c_str();
    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This should come with at least a short discussion of the lifetime of the buffer pointed to by json.
2

Possible solutions that come to mind:

std::string json_str;
const char* json = json_str.c_str();

You can use json as long as json_str is alive.

std::string json_str;
const char* json = strdup(json_str.c_str());

You can use json even after json_str is not alive but you have to make sure that you deallocate the memory.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.